문제

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();


}

}
도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top