Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to know whether an Activity has been destroyed

Tags:

android

May I know what is the proper way to know whether an Activity has been destroyed? Currently, I am using the following way.

private volatile boolean isOnDestroyCalled = false;

@Override
protected void onDestroy() {
    super.onDestroy();
    isOnDestroyCalled = true;
}

public boolean isOnDestroyCalled() {
    return this.isOnDestroyCalled;
}

Is there any other way better than the above?

like image 508
Cheok Yan Cheng Avatar asked Jul 10 '12 08:07

Cheok Yan Cheng


People also ask

When an activity is destroyed?

A: When you rotate the device, the activity is destroyed and a new one is created in its place. If we'd put code to set the stopwatch running again in the onRestart() method instead of onStart() , it wouldn't have run when the activity was recreated. The onStart() method gets called in both situations.

How do you check if activity is finished or not?

Using activity. isFinishing() is the right one solution. it return true if activity is finished so before creating dialog check for the condition. if true then create and show dialog.

What method is called in an activity when it is destroyed?

OnDestroy. OnDestroy is the final method that is called on an Activity instance before it's destroyed and completely removed from memory. In extreme situations Android may kill the application process that is hosting the Activity, which will result in OnDestroy not being invoked.

Which method is invoked when the activity is started?

onStart() When the activity enters the Started state, the system invokes this callback. The onStart() call makes the activity visible to the user, as the app prepares for the activity to enter the foreground and become interactive. For example, this method is where the app initializes the code that maintains the UI.


1 Answers

That will work, but sometimes the OS will go and shut your application down if it's inactive an amount of time when other applications need priority. For sure I know when that happens the variables will get nullified, not sure though if it would in your case using volatile which goes to main memory. But one way to be sure that you get the right value, is to save it in SharedPreferences.

like image 150
Carnal Avatar answered Oct 30 '22 06:10

Carnal