java 如何将上下文传递给 AsyncTask?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37531862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:35:57  来源:igfitidea点击:

How to pass Context to AsyncTask?

javaandroid

提问by Darshan Dhoriya

How to pass context in Async Taskclass which is coded in different java file from Main Activitybut it called from main activity?

如何在Async Task类中传递上下文,该类是在不同的 java 文件中编码的,Main Activity但它是从主活动调用的?

Below is my code:

下面是我的代码:

 @Override

protected void onPostExecute(List<Movie_ModelClass> result) {
        super.onPostExecute(result);

        if (result != null) {
            Movie_Adapter movieAdapter = new Movie_Adapter(new MainActivity().getApplicationContext() , R.layout.custom_row, result);
            MainActivity ovj_main = new MainActivity();
            ovj_main.lv_main.setAdapter(movieAdapter);
        } else {
            Toast.makeText(new MainActivity().getApplicationContext() ,"No Data Found", Toast.LENGTH_LONG);

        }
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
    }

回答by earthw0rmjim

You could just pass a Contextinstance as a constructor parameter (and keep a WeakReferenceto it to avoid memory leaks).

您可以将一个Context实例作为构造函数参数传递(并保留WeakReference它以避免内存泄漏)。

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();

回答by Tristan

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

您可以在 AsyncTask 的构造函数中传递上下文。

MyAsyncTask.java

我的异步任务.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.

然后在您的 onPostExecute() 方法中使用 mContext 变量。

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

当您从 MainActivity 调用 AsyncTask 时,会将上下文传递给 MyAsyncTask 的构造函数。

MainActivity.java

主活动.java

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

回答by Hymanson

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

我在尝试使用 Async 类压缩图像时遇到了同样的问题。我有一个构造函数,所以我只是添加了如下上下文

   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){

public void uploadDevicePhoto(Uri imageUri){

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

}

}