How to correctly start activity from PostExecute in Android?

后端 未结 3 1300
感动是毒
感动是毒 2020-11-28 11:42

I have an AsyncTask, that fills a custom List with parsed data from Internet.

In PostExecute I fill that List and get it ready to transfer it to a new Activity.

3条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 12:26

    You should pass in the application context rather than a context from the local activity. I.e. use context.getApplicationContext() and save that in a local variable in your AsyncTask subsclass.

    The code might looks something like this:

    public class MyAsyncTask extends AsyncTask {
    
        Context context;
        private MyAsyncTask(Context context) {
            this.context = context.getApplicationContext();
        }
    
        @Override
        protected Object doInBackground(Object... params) {
            ...
        }
    
        @Override
        protected void onPostExecute(List result) {
            super.onPostExecute(result);
            MainActivity.progressDialog.dismiss();
    
            context.startActivity(new Intent(context, ResultsQueryActivity.class));
        }
    }
    

    you'd call it like this:

       new MyAsyncTask(context).execute();
    

提交回复
热议问题