Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activity OnDestroy never called?

I am using following code in my ListActivity

// a separate class in project public class MyActivity extends ListActivity {     // some common functions here.. }  public class SelectLocation extends MyListActivity {      public void onCreate(Bundle savedInstance) {         // here.....     }      @Override     protected void onDestroy() {         super.onDestroy();         if (adap != null) adap = null;         if (list != null) list = null;         System.gc();     } } 

any one guide me why onDestroy method is not called in my code?

like image 394
UMAR-MOBITSOLUTIONS Avatar asked Dec 15 '10 12:12

UMAR-MOBITSOLUTIONS


People also ask

Is activity onDestroy always called?

onDestroy() is not always called. If called, only part of the code is executed.

What is onDestroy () activity?

onDestroy: The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it), or because the system is temporarily destroying this instance of the activity to save space. Here is an example...... public void onDestroy() { super.

Can the system destroy an activity without calling onDestroy?

You don't need to call stop( ) method. Android system automatically go thru those life cycle methods. But apparently onDestroy() always called after onStop() . If you want to kill activity just call finish() , it will destroy your activity.


2 Answers

onDestroy() is called only when system is low on resources(memory, cpu time and so on) and makes a decision to kill your activity/application or when somebody calls finish() on your activity.

So, to test your code() you can make a test button, that will call finish() on your activity.

Read more here.

Also, I believe you don't need to call all this stuff in onDestroy() until adap is not a critical resource. And even in that case android system has mechanisms to properly dispose them.

like image 115
Vladimir Ivanov Avatar answered Oct 15 '22 12:10

Vladimir Ivanov


There is no guarantee that your onDestroy method will be called at all.

The code that you are using in your onDestroy method is not needed at all. If destroy is called your acitivity will be removed from the stack and is free for garbage collection anyway with all the resources in it that are only referenced by the activity. Also System.gc() is supposed to be bad style. On Android the system nearly always knows when it is the best time to do a garbage collection. Most of the times an activity finishes garbage collection is triggered automatically. Just remove the whole onDestroy method. If you have problems with the overall memory of your application the problem is somewhere else.

like image 38
Janusz Avatar answered Oct 15 '22 11:10

Janusz