I'm making one part in my app where if you push the button then the phone will vibrate, and if you push the button again the phone will stop vibrating. I am using a Radio button for my button. my code is right now for the vibrate part:

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

The phone vibrates but it doesn't like vibrate with full power, and the radio button does not change. I am also unable to turn it off because the phone basically freezes. Anybody have any ideas to fix this?

有帮助吗?

解决方案

I've tried it myself. I think the code below is what you are looking for:

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();
            }
        }
    }
}

And here the layout:

<CheckBox
    android:id="@+id/checkBox1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="CheckBox"
    android:onClick="onCheckBox1Click"/>

其他提示

You programmed an infinite loop. Your device has no chance to change the state of your Radio Button because it's still in the while-loop.

One possibility is to start the vibration-code in a separate thread.

Another possibility is to add a Thread.Sleep(100) or so in your while loop.

You are using while loop hard.isChecked() which will be true forever, now it loops into infinite loop. so use a break statement in the while loop

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

or you can use the below code:

if(hard.isChecked()){
   vt.vibrate(1000);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top