简体   繁体   中英

Android finding out when activity destroyed

currently to find out when my app exits i'm using the onDestroy() to execute code which closes and sockets and turns bluetooth off. Now the only problem is that onDestroy() is not always called, so a signal can't be sent to the remote device that the app is exiting and the bluetooth doesn't turn off. Does anybody know of a way from which I can find out if the application is exiting 100% of the time?

Android grants to you the call of onPause() . onStop() and onDestroy() are not granted. Put your code in onPause() and onResume() .

It depends what you define as "when my app exits". Have a read through this page for more information: http://developer.android.com/training/basics/activity-lifecycle/starting.html

I would suggest placing the code in the onPause()

One popular method is to track your activities onPause() and onResume() callbacks and have a globalFlag like "appActivityStarted". Then implement following algorithm:

  • in onPause() set appActivityStarted = false AND start a Timer thread that will timeout after like 5 seconds
  • in onResume() set the appActivityStarted = true AND cancel the Timer
  • if the timeout occurs (was not cancelled) -> if (appActivityStarted == false) then you should do whatever you need to do on app stop
  • don't forget the appropriate synchronization on reading/setting the flag

I have extensively tested this approach and found no issues with it.

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