0

我在我的应用程序中做了一个部分,如果你按下按钮,手机就会振动,如果你再次按下按钮,手机就会停止振动。我正在为我的按钮使用单选按钮。我的代码现在用于振动部分:

                while(hard.isChecked()==true){
                    vt.vibrate(1000);
                }

手机会振动,但它不喜欢全功率振动,并且单选按钮不会改变。我也无法关闭它,因为手机基本上冻结了。有人有任何想法来解决这个问题吗?

4

3 回答 3

1

您编写了一个无限循环。您的设备没有机会更改单选按钮的状态,因为它仍处于 while 循环中。

一种可能性是在单独的线程中启动振动代码。

另一种可能性是在您的 while 循环中添加一个 Thread.Sleep(100) 左右。

于 2012-04-01T15:01:35.603 回答
1

您正在使用 while 循环 hard.isChecked() 这将永远为真,现在它循环进入无限循环。所以在while循环中使用break语句

while(hard.isChecked()==true){
    vt.vibrate(1000);
break;
 }

或者您可以使用以下代码:

if(hard.isChecked()){
   vt.vibrate(1000);
}
于 2012-04-01T15:02:08.817 回答
0

我自己试过了。我认为下面的代码是您正在寻找的:

private Vibrator vibrator;
private CheckBox checkbox;
private Thread vibrateThread;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    vibrator = ((Vibrator)getSystemService(VIBRATOR_SERVICE));
    checkbox = (CheckBox)findViewById(R.id.checkBox1);
    vibrateThread = new VibrateThread();
}

public void onCheckBox1Click(View view) throws InterruptedException{
    if(checkbox.isChecked()){
        if (vibrateThread.isAlive()) {
            vibrateThread.interrupt();
            vibrateThread = new VibrateThread();
        } else {
            vibrateThread.start();
        }
    } else{
        vibrateThread.interrupt();
        vibrateThread = new VibrateThread();
    }
}

class VibrateThread extends Thread {
    public VibrateThread() {
        super();
    }
    public void run() {
        while(checkbox.isChecked()){                
            try {
                vibrator.vibrate(1000);
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

这里的布局:

<CheckBox
    android:id="@+id/checkBox1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="CheckBox"
    android:onClick="onCheckBox1Click"/>
于 2012-04-09T06:56:26.733 回答