How To Kill A Thread And Handler Before Going To New Activity
Solution 1:
Thread.stop is deprecated call, instead you should use the Thread.interrupt method.
public void killCountdown(int waitTime){
progbar.setVisibility(0);
progbar.setProgress(0);
// deprecated: background.stop();background.interrupt(); // <-- OKbackground.join(waitTime); // optionally wait for the thread to exit
}
Thread.Interrupt
will cause a ThreadInterruptedException
next time your thread blocks or sleeps and you're already handling in your thread body so that's good. Additionally, you might want to include a volatile
flag that will allow you to stop the thread when it's not blocking or sleeping, but that's optional.
Solution 2:
You might consider using an AsyncTask instance instead of a runnable and a handler.
If you need to cancel an AsycnTask instance just call .cancel(true)
on your AsyncTask object reference. This will take care of both the background method (doInBackground()
) and the progress updater (onProgressUpdate()
).
I generally find AsyncTask easier to use than trying to handle all the details myself.
So, inside RMO_Dialog, use call execute()
on an instance of a class you create that extends AsyncTask.
publicclassRMO_DialogextendsActivity {
...
// Get ref to your bg task for easily cancellation if neededPassWordEntry background = newPassWordEntry();
// Start bg task
background.execute([PARAMS]);
...
// Cancel task
background.cancel(true);
...
// AsyncTask lets you encapsulate both your runnable and handler in itprivatestaticclassPassWordEntry() extendsAsyncTask<[PARAMS], [PROGRESS], [RESULT]> {
protected [RESULT] doInBackground() {
... // Runnable stuff herereturn [RESULT];
}
protectedvoidonProgressUpdate([PROGRESS]... progress) {
... // progressHandler stuff here
}
protectedvoidonPostExecute([RESULT]) {
// Clean up return data when all done w BG here
}
}
}
Post a Comment for "How To Kill A Thread And Handler Before Going To New Activity"