Question

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?

Was it helpful?

Solution

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"/>

OTHER TIPS

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top