Issue
I want to be able to execute some logic when my Android application is launched and also when it exits. I understand that there is not really a concept of this as such in Android, as each activity has its own lifecycle.
Suppose I have activities A, B, C & D and A is the root activity.
Application launch:
I could put the logic in
onCreate()
for A, but this is also called when the orientation is changed and (possibly, if memory is low) if the user hits theBack
key from activity B, C or D.I could create a class that extends
Application
and put the logic inonCreate()
. I tried this, butonCreate()
was not called in the scenario where I press theHome
key and then re-launch the application by clicking on the relevant icon in the main menu.
Application exit:
I could put logic in
onStop()
oronDestroy()
for all activities, but again I need to be able to tell if this is not being called as a result of a transition to another activity in my application. Also, there is no guarantee that these functions will be called when there is low memory?.I could override onLeaveUserHint() in all activities - are there any drawbacks to doing this?.
Edit (as requested by CommonsWare):
"Application launch" - my interpretation of an application launch is when one of the activities in my activity is being displayed after none of them when displayed (e.g. the user clicked on my application icon in the main menu).
"Application exit" - my interpretation of an application "exit" is when none of my activities are being displayed as a result of the user intentionally leaving an activity after one of them were displayed (e.g. by pressing the "Home" key or "Back" key).
(I hope this provides some clarification).
Solution
If you need to put your "Logic" in Activity and call it only once on start of app and on exit you can do something like:
App starts, you check in shared preferences is the app started for the first time - if yes -> Do your logic and save in shared preferences that you are finished.
You can override onBackPressed() when user finishes with the app, do whatever you like and save whatever state of the app you need so that you can again call your "logic" when app starts again.
Is that what you had in mind ?
Answered By - v0d1ch
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.