Program development often has the need to stop the thread running immediately, but through the API there is no way to achieve this purpose, so for this situation, we need to take some "special" way to achieve:
1, the method of judging the sign:
We need to know that there is no way to stop a running thread in a Java thread. The same is true for Android Asynctask. If you have to stop a thread, we can use this thread to set a flag bit, and then determine whether or not to continue execution by determining this flag bit with the key step in the inline run method or the Asynctask Doinbackground method. The flag bit is then changed where the thread needs to be terminated to achieve the purpose of stopping the thread.
2, reasonable use of exception
Calling Asynctask from the outside of the Cancel method does not stop a asynctask that has already started. This cancel method is similar to the thread's interrupt method, and the thread is still running after calling the interrupt method of a thread, but if the thread's Run method calls the sleep or wait method after it has been called, the Then sleep and wait end immediately and throw a Interruptedexception exception. The Asynctask Cancel method is the same, if the sleep or wait method is called in the Doinbackground method of the task, when the Cancel method of the task instance is called in the UI thread, Sleep or wait ends immediately and throws a Interruptedexception exception, but if there is additional code behind the code that catches the exception, the code will continue to execute.
3, you can tamper with the UI.
If the user in the background line is impersonating get content when the behavior of cancellation, we can according to the user's behavior in the UI immediately to make feedback, at this time, even if the thread completed the data loading, we do not let the data display, is a kind of opportunistic way.
This article is from the Linux commune website (www.linuxidc.com) Source Link: http://www.linuxidc.com/Linux/2013-03/81041.htm
Some ways to stop asynctask and thread immediately in Android development