What happens to an AsyncTask when the launching activity is stopped/destroyed while it is still running?

前端 未结 2 475
春和景丽
春和景丽 2020-12-16 02:55

I\'ve seen few questions nearly identical to mine, but I couldn\'t find a complete answer that satisfies all my doubts.. so here I am.. Suppose that you have an activity wit

相关标签:
2条回答
  • 2020-12-16 03:10

    The doInBackground() will keep on running even if your Activity gets destroyed(i,e your main thread gets destroyed) because the doInBackground() method runs on the worker's/background thread. There will be a 'problem' in running the onPostExecute() method as it runs on the main/UI thread and you may experience running into unrelated data but there will be no exception shown to the user. Thus, it is always better to cancel your AsyncTask when your activity gets destroyed as there is no reason to run AsyncTask when the Activity is no longer present. Use android Service if you continuously want to download something from the network even when your Component/Activity gets destroyed. Thanks.

    0 讨论(0)
  • 2020-12-16 03:13

    Consider this Task (where R.id.test refers to a valid view in my activity's layout):

    public class LongTaskTest extends AsyncTask<Void, Void, Void>{
        private WeakReference<Activity> mActivity;
        public LongTaskTest(Activity a){
            mActivity = new WeakReference<Activity>(a);
        }
        @Override protected Void doInBackground(Void... params) {
            LogUtil.d("LongTaskTest.doInBackground()");
            SystemClock.sleep(5*60*1000);
            LogUtil.d("mActivity.get()==null " + (mActivity.get()==null));
            LogUtil.d("mActivity.get().findViewById(R.id.frame)==null " + (mActivity.get().findViewById(R.id.test)==null));
            return null;
        }
    }
    

    If I run this task from an Activity's onCreate like so:

    public class Main extends Activity {
        @Override
        public void onCreate(Bundle state) {
            super.onCreate(state);
            setContentView(R.layout.testlayout);
            new LongTaskTest(this).execute();
            finish();
        }
    }
    

    No matter how long I sleep the background thread, my log always shows:

    LongTaskTest.doInBackground()
    mActivity.get()==null false
    mActivity.get().findViewById(R.id.frame)==null false
    

    Which is to say that the activity and its views appear to stay alive (even if I manually issue GCs via DDMS). If I had more time I'd look at a memory dump, but otherwise I don't really know why this is the case ... but in answer to your questions it appears that:

    • Does it silently fail? No
    • Does it produce any exception? No
    • Will the user be notified that something has gone wrong? No
    0 讨论(0)
提交回复
热议问题