Search code examples
androidandroid-vibration

Vibrate device on long button press


I want the device to vibrate as long as the user clicks the button. If the user press the button for a long period of time the device is to vibrate as long as the user clicks and holds. here is what I implemented but it works for a particular period of time.

final Button button = (Button) findViewById(R.id.button1);

button.setOnLongClickListener(new OnLongClickListener() {   

    @Override
    public boolean onLongClick(View v) {
        if(v==button){
            Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            vb.vibrate(1000);
       }                
       return false;
    }
});

Solution

  • To vibrate indefinitelly you can use vibration pattern:

    // 0 - start immediatelly (ms to wait before vibration)
    // 1000 - vibrate for 1s
    // 0 - not vibrating for 0ms
    long[] pattern = {0, 1000, 0};
    vb.vibrate(pattern, 0);
    

    Vibration can be cancelled using:

    vb.cancel();
    

    Start vibration on onTouch event - ACTION_DOWN, stop vibration on ACTION_UP

    EDIT: final working code:

        final Button button = (Button) findViewById(R.id.button1);
        button.setOnTouchListener(new OnTouchListener() {
            Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        long[] pattern = {0, 1000, 0};
                        vb.vibrate(pattern, 0);
                        break;
                    case MotionEvent.ACTION_UP:
                        vb.cancel();
                        break;
                }
                return false;
            }
        });