0

I have an activity that vibrates the phone for 9 seconds after it starts. I want the vibration action to be canceled when the activity leaves the foreground. Here is my current code:

     Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            // change image
             screen.setImageResource(R.drawable.yama);

             vibrateMe();
        }
    }, 9000);



        }


public void vibrateMe() {


    Vibrator vibrate = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);

    vibrate.vibrate(2000);
}


public void stopVibrating(Vibrator vibrate) {

    vibrate.cancel();
}

@Override
  public void onDestroy() {
    super.onDestroy();


}

}
Joel
  • 4,732
  • 9
  • 39
  • 54
A.Jouni
  • 377
  • 2
  • 4
  • 14
  • 2
    If you want to stop when the user leaves your Activity, you want to override `onPause()` instead; `onDestroy()` might not necessarily be called. I still don't see what the problem is though. – A--C Jan 07 '13 at 21:45
  • when i leave the app the phone still vibrates after 9 seconds ! This is the problem :D – A.Jouni Jan 07 '13 at 21:54

2 Answers2

2

You want to cancel your runnable? There are 2 options:

Community
  • 1
  • 1
Leonidos
  • 10,482
  • 2
  • 28
  • 37
0

You can cancel all CallBacks and Messages using removeCallbacksAndMessages();

public final void removeCallbacksAndMessages (Object token)

Added in API level 1 Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

apollosoftware.org
  • 12,161
  • 4
  • 48
  • 69