问题
I am building one of those SOS apps. Whenever the device is shaken above a threshold value (detected through accelerometer), I am showing a Toast
(as of now)
1) App is launched. User gives name, email, etc.. and clicks finish
on last screen.
2) Service
is started which keeps listening for shake.
3) It detects the shake correctly if the App is running.
4) If I close the app (the activity
), the service gets killed along with it.
How do I keep the service
running even if app is closed, so that it can listen to shakes from background? (That's the whole purpose of this app)
[1.I am returning START_STICKY in onStartCommand
I also tried using a
BroadcasterReciever
which will restart service by receiving broadcast fromonTaskRemoved
I am testing on ASUS Xenfone Max, Marshmallow OS ]
回答1:
You have two options:
- Start your service as foreground service (with
startForeground(int id, Notification notification)
: docs. But in this case you will have to show Notification in notification tray for as long as your service is running - Use separate process for your service adding in manifest to your process
android:process=":nameofyourprocess"
回答2:
Try starting a service without binding it to the activity (Simple unbound service). Return null
on your onBind()
function. Sticky services attach itself to a activity and has a lifetime as long as the attachment survives. You might have a constant notification related to your application when you use foreground services.
回答3:
You can put a Service in foreground, in which case it will always be considered as active (and it will therefore have its own notification, so the user knows that an active Service is running). It won't be stopped until it goes back to background. That is what you want in your case, as you want your Service to stay alive as long as possible. As described in the Android Service documentation:
A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory.
The idea is the same for Activities and Services, actually: when Android needs memory, it starts killing processes. The foreground processes (e.g. the Activity that is displayed on the screen, or foreground services) have a higher priority than the ones that are in background (say, a paused Activity), so they will be the last ones to be stopped by the system.
Using START_STICKY just tells the system that if it has to kill your Service, then you'd like it to restart it can. That doesn't say this Service is higher priority than the others.
来源:https://stackoverflow.com/questions/42338215/keep-android-service-running-even-after-activity-is-closed