Finish the calling activity when AsyncTask completes

Atul Goyal picture Atul Goyal · Dec 24, 2011 · Viewed 28.6k times · Source

My calling activity:

public class Hello extends Activity {  

public void onCreate(Bundle savedInstanceState) {

    MyTask mt = new MyTask(this);
    mt.execute();
}

Now In MyTask (an external class):

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

public MyTask(Context context) {

    mContext = context;
}  

//doinbackground, etc

    protected void onPostExecute() {
    mContext.finish();

}

Other things are working as expected if I remove mContext.finish() above.
But if I'm calling mContext.finish() , I'm getting an error: The method finish() is undefined for the type Context (Eclipse doesn't show finish() when I write mContext. so that suggests I'm using finish() wrongly.)

What do I need to do to finish the calling activity Hello after MyTask completes the task

Answer

Squonk picture Squonk · Dec 24, 2011
((Activity)mContext).finish();

Would be the correct way to cast a Context to an Activity and call its finish() method. Not sure why you'd want to finish an Activity from an AsyncTask though