Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finish the calling activity when AsyncTask completes

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

like image 658
Atul Goyal Avatar asked Dec 24 '11 09:12

Atul Goyal


People also ask

When AsyncTask is executed it goes through what steps?

An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .

How do you wait for an async task to finish?

You will need to call AsyncTask. get() method for getting result back and make wait until doInBackground execution is not complete.

How many times an instance of AsyncTask can be executed?

AsyncTask instances can only be used one time.

Why is AsyncTask deprecated?

This class was deprecated in API level 30.AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.


1 Answers

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

like image 163
Squonk Avatar answered Oct 22 '22 00:10

Squonk