javaandroidvibration

Vibrate until the button is pressed and stops vibrating when the button is unpressed (or the finger is taken off)


I am planning to program a button in such a way that when the button is pressed, vibration starts and keeps on vibrating until the finger is up or button is unpressed.

I am using OnTouchListener for this purpose.

My code is as follows:

package com.example.vibrator;

import android.app.Activity;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Vibrator vibrator;

        vibrator = (Vibrator) getSystemService(MainActivity.VIBRATOR_SERVICE);

        Button btn = (Button) findViewById(R.id.button1);
        btn.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();

                if (action == MotionEvent.ACTION_DOWN) {
                    vibrator.vibrate(60000);
                } else if (action == MotionEvent.ACTION_UP) {
                    vibrator.cancel();
                }

                return true;
            }
        });
    }
}

The problem in this code is that it keeps on vibrating and when the finger is up, the vibration does not stop nor cancelled.

P.S. I have used the permission in manifest.


Solution

  • EDIT: corrected code:

    try this:

    int action = event.getActionMasked();
    
    if (action == MotionEvent.ACTION_DOWN) {
        long[] pattern = { 0, 200, 0 }; //0 to start now, 200 to vibrate 200 ms, 0 to sleep for 0 ms.
        vibrator.vibrate(pattern, 0); // 0 to repeat endlessly.
    } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
        vibrator.cancel();
    }