如何将上下文传递给 AsyncTask?

问题描述 投票:0回答:4

我想在后台任务完成时执行

Toast
,只是为了让用户知道它已完成。

我为我的 asyncTask 创建了一个新类,但我无法在该类中使用

getApplicationContext()

我正在使用

task.execute(getTempFile(this), getApplicationContext());
来运行任务。 getTempFile 返回一个 File 对象,我试图将上下文作为 Context 对象传递。

我的任务类有三个变量,

AsyncTask<Object, Integer, Integer>
,所以上下文在第二个对象中。但是,这会使应用程序崩溃。

public class LocationActivity extends Activity implements LocationListener {
    protected void handleImage(Bitmap thumbnail) {
        PushDataToServer task = new PushDataToServer();
        task.execute(getTempFile(this), getApplicationContext());
    }
}


public class PushDataToServer extends AsyncTask<Object, Integer, Integer> {

    Context context;

    @Override
    protected Integer doInBackground(Object... params) {
        // TODO Auto-generated method stub
        this.context = (Context) params[1];
        File file = (File) params[0];
        return null;
    }

    protected void onPostExecute(String result) {
         Toast toast = Toast.makeText(this.context, "All done!", Toast.LENGTH_SHORT);
         toast.show();
    }

}
java android android-asynctask
4个回答
78
投票

Context
对象传递到
AsyncTask
的构造函数中。

示例代码:

public class MyTask extends AsyncTask<?, ? ,?> {
    private Context mContext;

    public MyTask(Context context) {
        mContext = context;
    } 
}

然后,当你构建你的

AsyncTask
时:

MyTask task = new MyTask(this);
task.execute(...);

2
投票

在构造函数中传递它,而不是作为方法参数。那么你就不需要依赖通用参数了。


1
投票

完整示例:可重用AsyncTask


0
投票

你说你的上下文在第二个对象中,但你的第二个对象是 Integer。这可能是你的问题吗?另外 - 另一个建议是将您的 AsyncTask 类作为私有内部类放入您的活动 - 这样我很确定您将有权访问 getApplicationContext()。

© www.soinside.com 2019 - 2024. All rights reserved.