AsyncTask will always run even if app is destroyed?

前端 未结 5 860
孤街浪徒
孤街浪徒 2020-12-31 04:36

I have an application and because you can\'t do network operations on the main thread I\'m using AsyncTask, so the question is once I execute() the

5条回答
  •  长发绾君心
    2020-12-31 05:19

    You will be able to test this. And yes It does. If execute was called you can see Asynctask will still execute UNLESS it does something to the forground or UI related. (it may cause launcher to crash).


    However, if it was close by the system. It may or may not continue executing the method. I have already tested and answered here. Reply to comment: Tested:

    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            new Worker().execute();
        }
    private class Worker extends AsyncTask {
    
        @Override
        protected String doInBackground(Void... arg0) {
            Log.i("SomeTag",
                    "start do in background at " + System.currentTimeMillis());
            String data = null;
    
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(
                        "https://stackoverflow.com/questions/tagged/android");
    
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                data = EntityUtils.toString(httpEntity);
                Log.i("SomeTag",
                        "doInBackGround done at " + System.currentTimeMillis());
            } catch (Exception e) {
            }
            return data;
        }
    
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Log.i("SomeTag", System.currentTimeMillis() / 1000L
                    + " post execute \n" + result);
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("SomeTag", System.currentTimeMillis() / 1000L + "  onDestory()");
    }
    
    04-24 21:42:57.981: I/SomeTag(5961): start do in background at 1366854177994
    04-24 21:43:00.974: I/SomeTag(5961): 1366854180  onDestory()
    04-24 21:43:02.946: I/SomeTag(5961): doInBackGround done at 1366854182946
    04-24 21:43:02.946: I/SomeTag(5961): 1366854182 post execute 
    04-24 21:43:02.946: I/SomeTag(5961): 
    04-24 21:43:02.946: I/SomeTag(5961): 
    04-24 21:43:02.946: I/SomeTag(5961): 
    04-24 21:43:02.946: I/SomeTag(5961):         
    04-24 21:43:02.946: I/SomeTag(5961):     Newest 'android' Questions - Stack Overflow
    04-24 21:43:02.946: I/SomeTag(5961):     
    //....
    

提交回复
热议问题