简体   繁体   中英

How to know when an application finished?

I need to know when an application finishes to stop all the local services that it starts.

How can I do it?

You could try using onDestroy() (not recommended, though) to know when Android is cleaning your app from the memory. or can also use onStop() to know when the Activity is being sent in the background.
Do implement these two methods in the first activity of the Activity stack.

Lets see if it helps, since I also haven't tried it so far.

One idea is to use BoundService despite the fact that it's your app own service. By definition Bound Service stops when the las connection is dropped.

Another idea would be to define count in Application object (you can override global Application object). You can increment the count in each onResume and in decrement in each onPause.

  1. You could use try / finally on the main function and do the service clean up in the final block

  2. You could use object finalizer to issue shutdown commands. You wont know exactly when it happens since the Garbage collector will run at its own pace, but you do know it will happen eventually.

I am now solving the same problem, I have an Idea and will implement it: 1.static variable called (String currentShownActivity). 2. in every Activity (onResume() ) I fill the variable with activity name). So when I navigate between the activities the currentShownActivity variable changed and carry the current activity name. 3. on every onPause(), set flag that indcate the activity onPause() called (ie boolean IsPauseCalled) 4.in onStop () check IsPauseCalled, and the activity name. if the activity onPause called and the name in currentShownActivity not changed (that mean we leave the activity to "no activity") and that mean [home] key pressed.

the integration way to know the the application is not running Check onDestroy of the main activity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM