Created
February 12, 2014 08:38
-
-
Save showsky/8951906 to your computer and use it in GitHub Desktop.
AsyncTask safe stop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 在使用 AsyncTask 停止常常被人忽略的問題以下兩種。 | |
| 1. 呼叫了 cancel() 但是沒有馬上停止而造成其他 crash。 | |
| 2. Activity 已經被 onDestory 但是 AsyncTask 沒有被 cancel 造成 crash。 | |
| */ | |
| public class MainActivity extends Activity { | |
| private final static String TAG = "MainActivity"; | |
| private AsyncTask<Void, Void, Boolean> async; | |
| private Handler handler = new Handler(); | |
| @Override | |
| protected void onCreate(Bundle savedInstanceState) { | |
| super.onCreate(savedInstanceState); | |
| setContentView(R.layout.activity_main); | |
| async = new AsyncTask<Void, Void, Boolean>() { | |
| @Override | |
| protected void onPreExecute() { | |
| super.onPreExecute(); | |
| Log.d(TAG, "onPreExecute()"); | |
| } | |
| @Override | |
| protected Boolean doInBackground(Void... params) { | |
| try { | |
| for (int i = 0; i< 10; i++) { | |
| Log.d(TAG, "i = " + i); | |
| Thread.sleep(1000); | |
| } | |
| } catch (InterruptedException e) { | |
| e.printStackTrace(); | |
| Log.e(TAG, "InterruptedException"); | |
| } | |
| return true; | |
| } | |
| @Override | |
| protected void onCancelled() { | |
| super.onCancelled(); | |
| Log.d(TAG, "onCancelled()"); | |
| } | |
| @Override | |
| protected void onCancelled(Boolean result) { | |
| super.onCancelled(result); | |
| Log.d(TAG, "onCancelled(result): " + String.valueOf(result)); | |
| } | |
| @Override | |
| protected void onPostExecute(Boolean result) { | |
| super.onPostExecute(result); // 不使用就不會呼叫 protected void onCancelled() | |
| Log.d(TAG, "onPostExecute"); | |
| } | |
| }.execute(); | |
| handler.postDelayed(new Runnable() { | |
| @Override | |
| public void run() { | |
| async.cancel(true); // 立即中止會引發 InterruptedException | |
| } | |
| }, 1000 * 3); | |
| } | |
| } | |
| /* | |
| [Log display] | |
| onCancelled() | |
| onCancelled(result): true | |
| [Readme] | |
| 1. 可以在 doInBackground() 做 isCancelled() 檢查,提早做結束 | |
| [Ref] | |
| http://www.cnblogs.com/wangfenjin/archive/2012/09/21/2696905.html | |
| http://blog.csdn.net/snow4dev/article/details/8809897 | |
| */ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment