Android destroy activity and object and open new activity

In Android, when an activity is destroyed, its objects and resources are also released. Here's a step-by-step guide on how to destroy an activity, release its objects, and open a new activity:

Destroying an activity

To destroy an activity, you can use the finish() method, which is a part of the Activity class. This method will remove the activity from the back stack and release its resources.

public class MyActivity extends AppCompatActivity {
    //...

    @Override
    public void onDestroy() {
        super.onDestroy();
        finish();
    }
}

Releasing objects

To release objects, you can use the onDestroy() method, which is called when the activity is being destroyed. In this method, you can release any objects that you no longer need.

public class MyActivity extends AppCompatActivity {
    private MyObject myObject;

    //...

    @Override
    public void onDestroy() {
        super.onDestroy();
        finish();
        if (myObject!= null) {
            myObject.releaseResources();
            myObject = null;
        }
    }
}

Opening a new activity

To open a new activity, you can use the Intent class. Create a new Intent object and set the class of the activity you want to open as the target.

public class MyActivity extends AppCompatActivity {
    //...

    public void openNewActivity() {
        Intent intent = new Intent(this, NewActivity.class);
        startActivity(intent);
    }
}

Example

Here's an example of how you can destroy an activity, release its objects, and open a new activity:

public class MyActivity extends AppCompatActivity {
    private MyObject myObject;

    //...

    @Override
    public void onDestroy() {
        super.onDestroy();
        finish();
        if (myObject!= null) {
            myObject.releaseResources();
            myObject = null;
        }
    }

    public void openNewActivity() {
        Intent intent = new Intent(this, NewActivity.class);
        startActivity(intent);
    }
}

In this example, when the MyActivity is destroyed, it releases its objects and opens a new NewActivity using the Intent class.

Note

When you destroy an activity, its objects and resources are released, but the activity itself is not completely removed from memory. The activity is still present in the back stack, and you can return to it by pressing the back button. If you want to completely remove the activity from memory, you can use the finishAndRemoveTask() method instead of finish().