一遍又一遍地运行一个功能

时间:2011-03-27 18:10:02

标签: android

我刚开始为Android编写应用程序。我有非面向对象程序语言的程序编写经验,但也希望学习这种编程方式。

我想从简单开始并执行以下操作: 按下按钮,将以特定模式触发手机的振动器,直到再次按下该按钮

我知道如果你说:vibrator.vibrate(pattern,0);它会重复这种模式。但是我想以这种模式开启和关闭屏幕。

这样做的正确方法是什么?

非常感谢你的帮助。

package com.trick-design.simple_prog;

import android.app.Activity;
import android.os.Bundle;
import android.content.Context;
import android.os.Vibrator;
import android.view.View;


public class simple_prog extends Activity {
private long[] pattern = {100, 100, 300, 100, 900, 1050};
boolean vibrator_on = true;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}
@Override
protected void onStart() {
    super.onStart();
    findViewById(R.id.vibrate_button).setOnClickListener(vibrate_click_listener);
}

View.OnClickListener vibrate_click_listener = new View.OnClickListener() {
    public void onClick(View v) {

        Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(pattern , -1);
   }
};

@Override
protected void onStop() {
    super.onStop();
    // The activity is no longer visible (it is now "stopped")
}
@Override
protected void onDestroy() {
    super.onDestroy();
    // The activity is about to be destroyed.
    } 

}

2 个答案:

答案 0 :(得分:1)

试试这个:

public void vibrate() {
    vibrator.vibrate(pattern , -1);
    if(vibrator_on) {
        vibrate();
    }
}

此方法将重复进行,直到vibrate_onfalse。 (确保它在自己的线程中运行,否则只要vibrate_ontrue,它就会冻结运行它的任何线程。

<强>更新 正如评论中所讨论的那样,这并不好。 这应该做得更好:

public void doVibrate() {
    while(vibrate_on) {
        executeVibrate();
    }
}

public void executeVibrate() {
    vibrator.vibrate(pattern , -1);
}

答案 1 :(得分:1)

作为TVK答案的延伸:

您需要创建一个实现Runnable或扩展Thread的类,以便在另一个线程中执行此操作以防止挂起。您可以在同一个* .java文件中使用第二个类来执行此操作 - 允许它从文件中的其他类访问变量:

private class VibrateRunner implements Runnable
{
    public void run()
    {
       while(vibrate_on)
       {
           executeVibrate();
       }
    }

    private void executeVibrate()
    {
       vibrator.vibrate(pattern , -1);
    }
}

你的点击监听器需要足够聪明才能启动/停止线程 - 例如:

// Make a Thread class variable
Thread bgThread = null;

onClick(View v)
{
    // You already started the thread - stop it
    if(bgThread != null)
    {
       vibrate_on = false;
       bgThread.join();
       return;
    }

    // Need to turn on the thread
    vibrate_on = true;

    Runnable runner = new VibrateRunner();
    bgThread = new BackgroundThread(runner);
    bgThread.setDaemon(true); // Run it in the background
    bgThread.start();
}

这应该会让你走向正确的方向。注意:我在这里删除了很多异常处理 - 只需阅读一些Java线程就可以了解它。 Eclipse还将帮助您生成正确的try / catch块。

- 丹