Stop vibration in android when activity is finished

7.7k views Asked by At

I am running this on button click in my android app:

public void vibrateold() {
    Vibrator vibrate = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);

    vibrate.vibrate(4000);
}

But the vibration doesn't stop when leaving the activity before 4 seconds.How should I stop it ?

1

There are 1 answers

1
Philipp Jahoda On BEST ANSWER

How about the Vibrators method cancel()?

Vibrator.cancel();

For example: (Initialize and start vibrating in the onCreate() - if the activity is destroyed or paused before the 10 seconds of vibration run out, stop vibrating)

Vibrator vibrator;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    vibrator.vibrate(10000);
}

@Override
public void onPause() {
    vibrator.cancel();  // cancel for example here
}

@Override
public void onDestroy() {
    vibrator.cancel();   // or cancel here
}