0

I have an activity that runs the following:

    private void loop() {
            // TODO Auto-generated method stub

            handler.postDelayed(new Runnable() { 
            public void run() { 

            DBListern(); 
            handler.postDelayed(this, 5000);
        }
    }, 5000); 

}

I would like to cancel this handle on back button:

    public boolean onBackPress(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK) {

        handler.removeCallbacksAndMessages(null);

        return true;

    }

    return super.onKeyDown(keyCode, event);

}

The handler is still running after back button is pressed, how can I stop it?

TwoStarII
  • 351
  • 3
  • 17
  • 1
    Is this post duplicated? (http://stackoverflow.com/questions/22718951/stop-handler-postdelay) – wake-0 Jun 24 '16 at 08:59

4 Answers4

2

First of all the right name of the method you are looking for is onBackPressed(). So your code is simply not called by framework. Try

@Override
public void onBackPressed() {
    handler.removeCallbacksAndMessages(null);

    super.onBackPressed();
}
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
1

You need to do this way:

@Override
public void onBackPressed() {
    if(mHandler!=null){
        mHandler.removeCallbacks(mRunnable);
    }
    super.onBackPressed();        
}

Reason: You need to manually remove callback of Runnable from Handler onBackPress.

Hope this would help you.

Hiren Patel
  • 52,124
  • 21
  • 173
  • 151
0

public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName();

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

private void loop() {
    // TODO Auto-generated method stub

    handler.postDelayed(new Runnable() {
        public void run() {

           Log.i(TAG,"run");
            handler.postDelayed(this, 5000);
        }
    }, 5000);

}

Handler handler = new Handler();

@Override
public void onBackPressed() {
    super.onBackPressed();
    handler.removeCallbacksAndMessages(null);
}

}

this works for me.

Ganesh Kanna
  • 2,269
  • 1
  • 19
  • 29
-1

For removed handler messeges, you need set not null in method parametrs. Its Must bee lenk on object , or message type, what do yo like to remove. And why you made this chek if (keyCode == KeyEvent.KEYCODE_BACK) {

its realy nesesary?

Vitaliy Ptitsin
  • 329
  • 1
  • 5
  • 14
  • "If token is null, all callbacks and messages will be removed." https://developer.android.com/reference/android/os/Handler.html#removeCallbacksAndMessages(java.lang.Object) – Marcin Orlowski Jun 24 '16 at 09:09