How to pass Context to AsyncTask?

前端 未结 3 1119
余生分开走
余生分开走 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:45

    I encountered same issue when trying to compress an image using an Async class. I had a constructor in place so I just added context as below

       public BackgroundImageResize(Context context, Bitmap bm) {
        if (bm != null){
            mBitmap = bm;
        }
        this.context =context;
    }
    

    Then i called the class like below,

    public void uploadDevicePhoto(Uri imageUri){

    BackgroundImageResize resize = new BackgroundImageResize(this,null);
    resize.execute(imageUri);
    

    }

    0 讨论(0)
  • 2020-12-14 09:49

    You could just pass a Context instance as a constructor parameter (and keep a WeakReference to it to avoid memory leaks).

    For example:

    public class ExampleAsyncTask extends AsyncTask {
        private WeakReference<Context> contextRef;
    
        public ExampleAsyncTask(Context context) {
            contextRef = new WeakReference<>(context);
        }
    
        @Override
        protected Object doInBackground(Object[] params) {
            // ...
        }
    
        @Override
        protected void onPostExecute(Object result) {
            Context context = contextRef.get();
            if (context != null) {
                // do whatever you'd like with context
            }
        }
    }
    

    And the execution:

    new ExampleAsyncTask(aContextInstance).execute();
    
    0 讨论(0)
  • 2020-12-14 09:50

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

    MyAsyncTask.java

    public class MyAsyncTask extends AsyncTask<Void, Integer, List> {
    
        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();
    
    0 讨论(0)
提交回复
热议问题