How to pass Context to AsyncTask?

前端 未结 3 1131
余生分开走
余生分开走 2020-12-14 09:13

How to pass context in Async Task class which is coded in different java file from Main Activity but it called from main activity?

Below is

3条回答
  •  庸人自扰
    2020-12-14 09:50

    You can just pass the context in the constructor of your AsyncTask.

    MyAsyncTask.java

    public class MyAsyncTask extends AsyncTask {
    
        private final Context mContext;
    
        public MyAsyncTask(final Context context) {
             mContext = context;
        }
    }
    

    and then just use the mContext variable in your onPostExecute() method.

    When you call your AsyncTask from your MainActivity, you pass the context to the constructor of MyAsyncTask.

    MainActivity.java

    final MyAsyncTask task = new MyAsyncTask(getApplicationContext());
    task.execute();
    

提交回复
热议问题