0

I am stuck in a problem hope someone suggest me a solution. I am using

new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
}});

method to delay some task its woking fine. But before that delay completes If I hit back its crashing because the task needs to complete is expecting the context of the activity which is already closed. Can anybody help me to solve this issue?

Thanks

ImGenie
  • 323
  • 1
  • 15

3 Answers3

0

You have to add on-back pressed event and at that time you have stop all process so crashing problem are gone.

If you still have confusion then add your code so I can help you.

Sam Patel
  • 1
  • 3
0

Save a reference to the Runnable and use Handler#removeCallbacks(...) in one of your lifecycle methods, probably onPause(). If the task needs to outlive the activity, move it to a Service.

Kevin Krumwiede
  • 9,868
  • 4
  • 34
  • 82
0

You can remove the callback from the handler before going back by following code:

myHandler.removeCallbacks(yourRunnableInstance); // it will remove particular this Runnable

myHandler.removeCallbacksAndMessages(null); // it will remove all Runnable from the handler

you could do this code in onPause() method.

Jagdeep Singh
  • 1,200
  • 1
  • 16
  • 34