如何将上下文传递给 AsyncTask? [英] How do i pass a context to an AsyncTask?

查看:42
本文介绍了如何将上下文传递给 AsyncTask?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在后台任务完成时执行一个 Toast,只是为了让用户知道它已经完成.

I want to preform a Toast when a background task is completed, just to let the user know that it's finished.

我为 asyncTask 创建了一个新类,但我不能在这个类中使用 getApplicationContext().

I've made a new class for my asyncTask but i cannot use getApplicationContext() within this class.

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

I'm using task.execute(getTempFile(this), getApplicationContext()); to run the tasks. getTempFile returns a File object, and i was trying to pass the context as a Context object.

我的任务类有 3 个变量 AsyncTask 所以上下文在第二个对象中.但是,这会使应用程序崩溃.

My Task class has 3 variables AsyncTask<Object, Integer, Integer> so the context is in the second object. However, this crashes the application.

编辑

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

}

推荐答案

Context 对象传递给 AsyncTask 的构造函数.

Pass a Context object into the AsyncTask's constructor.

示例代码:

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

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

然后,当您构建 AsyncTask 时:

and then, when you are constructing your AsyncTask:

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

这篇关于如何将上下文传递给 AsyncTask?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆