Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for calling finish() on an activity in android?

Most of my activities load dynamic data from a server, and when the page comes back into focus, i reload it anyway. It seems wasteful to keep them around if I'm just going to reload them, so I thought of calling finish() on them if the user navigates away from the page.

Its confusing if some activities you can press the back button to go to and others no because I've called finish() on them, so I was wondering if its bad practice just to call finish() on all activities the user navigates away from? (I have a navigation bar at the bottom of every activity so the back button isnt necessary). Or, is it better practice not to call finish() on any of the activities and just hope they dont slow down the phone and that the OS will take care of garbage collecting them?

I'm new to Android programming and and don't have an Android phone so i'm not sure what is the common/best practice in this situation, or if its just a matter of personal taste.

Also, is it possible to instruct Android to keep a history of activities so that the back button still works, but finish() them when they navigate away so that they're not needlessly taking up resources?

like image 420
Mohamed Hafez Avatar asked Jul 12 '12 20:07

Mohamed Hafez


People also ask

What happens when you call finish () inside onCreate ()?

As per official documentation: You can call finish() from within this function, in which case onDestroy() will be immediately called after onCreate(Bundle) without any of the rest of the activity lifecycle (onStart(), onResume(), onPause(), etc) executing.

What is the use of finish () in Android?

On Clicking the back button from the New Activity, the finish() method is called and the activity destroys and returns to the home screen.

Does finish call onPause?

Android will generally call onPause() if you call finish() at some point during your Activity's lifecycle unless you call finish() in your onCreate() .


1 Answers

While you may reload all your data on returning to the activity, there is still no point on calling finish().

When activities are hidden, they do not use resources, and are of no real problem. Just leave them as is, and then when the user navigates back, it will reload it as required.

In this state, they can also be garbage collected if required - which is all taken care of by android.

like image 171
IAmGroot Avatar answered Oct 14 '22 07:10

IAmGroot