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

前端 未结 2 476
春和景丽
春和景丽 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:13

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

    public class LongTaskTest extends AsyncTask{
        private WeakReference mActivity;
        public LongTaskTest(Activity a){
            mActivity = new WeakReference(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

提交回复
热议问题