Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destroy an activity in Android?

Tags:

android

While the application is running, I press the HOME button to close the application. When I start the application again, it resumes on the page displayed prior to clicking on HOME. I want the application to start with the initial display instead. I have used finish() to finish the activity but it is not working. Any suggestions?

like image 961
Nikki Avatar asked Nov 09 '10 08:11

Nikki


People also ask

When can Android activity be destroyed?

Handling Configuration Changes The Activity lifecycle is especially important because whenever an activity leaves the screen, the activity can be destroyed. When an activity is destroyed, when the user returns to the activity, the activity will be re-created and the lifecycle methods will be called again.

What happens when an activity is destroyed Android?

When Android creates and destroys an activity, the activity moves from being launched to running to being destroyed. An activity is running when it's in the foreground of the screen. onCreate() gets called when the activity is first created, and it's where you do your normal activity setup.

What is on destroy in Android?

onDestroy() is a method called by the framework when your activity is closing down. It is called to allow your activity to do any shut-down operations it may wish to do.


1 Answers

Most likely you have several instances of the same activity. To resolve this kind of issues create your own parent Activity class e.g. MyRootActivity which will hold static list of all of available/alive activities:

public class MyRootActivity extends Activity
{
    private static final String TAG=MyRootActivity.class.getName();
    private static ArrayList<Activity> activities=new ArrayList<Activity>();


    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        activities.add(this);
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        activities.remove(this);
    }

    public static void finishAll()
    {
        for(Activity activity:activities)
           activity.finish();
    }
}

For that all of your activities need to be children of MyRootActivity.

Then when you are about to sure that you're closing your application - just call MyRootActivity.finishAll();

like image 73
Barmaley Avatar answered Sep 28 '22 02:09

Barmaley