I am currently writing an app for android that i need to start the service when I exit or pause the application. What should i do? In my application, every time when I click a thing, it will go to another activity, so i cannot put the startservice to the onpause inside those activity. What should I do?
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
Have a look at the Activity life cycle here: http://developer.android.com/reference/android/app/Activity.html
Android doesn't exit the activity when you start a new one, it just pauses it. So starting the service inside onPause() should be fine.
According to android life cycle,
onPause()
method will call as a first indication that user is leaving your activity. It may leave or not. So as per your requirement you canstartService.
But make sure don't put heavy code inside as it may effect user experience.When Activity is no longer visible, it calls
onStop()
. But still we can not be sure if app is destroyed as Android OS internally handles it. So try following steps to find if you app is inbackground
:Get the running task info using
If tasks list is not empty, check if running taks belongs to your app. If it belongs, then return true to the calling function, where you can start your service ; else return
false
Edit : This may be helpful : http://developer.android.com/reference/android/app/ActivityManager.html#getRunningAppProcesses
By overriding this methods you can check if your app is onPause or onDestroy