Android: How to Stop Runnable

Android: How do I stop Runnable?

Instead implement your own thread.kill() mechanism, using existing API provided by the SDK. Manage your thread creation within a threadpool, and use Future.cancel() to kill the running thread:

ExecutorService executorService = Executors.newSingleThreadExecutor();
Runnable longRunningTask = new Runnable();

// submit task to threadpool:
Future longRunningTaskFuture = executorService.submit(longRunningTask);

... ...
// At some point in the future, if you want to kill the task:
longRunningTaskFuture.cancel(true);
... ...

Cancel method will behave differently based on your task running state, check the API for more details.

How to stop Runnable on button click in Android?

Use

mHandler.removeCallbacksAndMessages(runnable);

in pause button click.

How do I stop a runnable when I start another activity?

Based on the documentation for removeCallbacksAndMessages

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

Your code won't match any token:
myHandler.removeCallbacksAndMessages(aMyRunnable);

So the solution would be to use:

myHandler.removeCallbacksAndMessages(null);

How to stop/cancel a runnable when pressing on android phone's back button?

Create your Handler as a member variable of your class, like this:

Handler myHandler = new Handler();

Create your Runnable as a member variable of your class, like this:

Runnable myRunnable = new Runnable() {
@Override
public void run() {
Intent restartExamAdditionActivity = new Intent(ExamAdditionActivity.this, ExamAdditionActivity.class);

overridePendingTransition(0, 0);
startActivity(restartExamAdditionActivity);
finish();
overridePendingTransition(0, 0);
}
};

Post the Runnable using the new variable:

myHandler.postDelayed(myRunnable, TIME_OUT);

When you want to cancel the regeneration, do this:

myHandler.removeCallbacks(myRunnable);

Android Stopping Runnable onBackPressed()

Finally got this to work. The NPE was due to not initializing the handler class wide. After I fixed that the runnable would still not stop with handler.removeCallbacks(runnable); What seems to be working is:

handler.removeCallbacksAndMessages(null);.



Related Topics



Leave a reply



Submit