Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

java - How do i pass a context to an AsyncTask?

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

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

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.

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

Edit

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

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Pass a Context object into the AsyncTask's constructor.

Sample code:

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

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

and then, when you are constructing your AsyncTask:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...