Do onDestroy () or finish () actually kill activity?

In fact, I know that I'm asking about a simple and basic Android concept. But I'm a little confused about these finish() and onDestroy() methods. Will it kill activity and free up resources associated with these actions?

I tried with a simple application that contains only one action. I thought the concept was similar. When the application starts, the action will begin. and when we press the back button, it will finish. And I gave some toast message in each life cycle to find out about memory usage. And when I clicked the back button, it did onPause() , onStop() and onDestroy() . I thought this activity was over. But when I resumed the application again, then it took up more memory than in the previous time. This happens every time I launch the application from eclipse or restart the application from the main screen.

Why is this happening? How can I actually destroy an application / activity to free up memory?


I am including the code. I just give only one toast message inside the class. Then increases memory usage.

Every time I run the application, the allocated size increases as: 3302744, 3442384, 3474552

  public class myActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Toast.makeText(getBaseContext()," allocated size = " + Debug.getNativeHeapAllocatedSize(), 1).show(); } } 

manifest:

 <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".myActivity " android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> 

Why is memory increasing every time?

+4
source share
3 answers

Finish () kills activity and frees memory ... if you don't have any link that has leaked ... for example, in methods like onRetainNonConfigurationInstance ()

When you click the back button, the finish () method is called, which calls onPause, onStop, onDestroy.

+13
source

The default behavior is that the back button will exit the activity and destroy it. However, showing a toast in onDestroy or onPause is not a good idea. This will change the life cycle of your activity the way you do not want it. Use logging instead, so you'll see what is actually happening. BTW, finish () is what you explicitly call from your code, and onDestroy () is an event / lifecycle method that is called as a result of completion / destruction of activity in any way.

+8
source

Finish () will literally end your activity, and if there are no links, GC will restore resources. onDestory () is actually a method that the system will call when it destroys your activity, and you must implement this function. You do not need to worry about destroying your application, android does it for you.

+2
source

Source: https://habr.com/ru/post/903426/


All Articles