androidradio-buttonvibrationischecked

android vibrator turn on and turn off


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?


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