Java how to destroy activity in android

Java how to destroy activity in android

To destroy an activity in Android, you can call the finish() method. This method finishes the activity and removes it from the activity stack.

Here's an example of how to use the finish() method to destroy an activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
  // ...
}

// Button click handler
public void onButtonClick(View view) {
  // Destroy the current activity
  finish();
}
Sou‮cr‬e:www.lautturi.com

Alternatively, you can use the finishAffinity() method to destroy an activity and all the activities that are in the same task as the activity. This method is useful if you want to finish all the activities in a task and return to the previous task.

Here's an example of how to use the finishAffinity() method to destroy an activity and all the activities in the same task:

@Override
protected void onCreate(Bundle savedInstanceState) {
  // ...
}

// Button click handler
public void onButtonClick(View view) {
  // Destroy the current activity and all the activities in the same task
  finishAffinity();
}

Note that calling finish() or finishAffinity() does not completely destroy the activity. It only marks the activity as finished and removes it from the activity stack. The system may still keep the activity in memory if it is part of a back stack of fragments. To completely destroy an activity and release all its resources, you can use the onDestroy() method, which is called when the activity is being destroyed.

Created Time:2017-11-03 22:21:05  Author:lautturi