Android Services and Activities
I have some questions about the Android service and activity lifecycles. Hope you guys can help me out. I have written an application that uses GPS location and stores them. It must monitor the GPS location updates constantly to work properly.
Right now, it's all in one activity. So when you close the activity, you loose everything and can't continue monitor location updates. This is why I wanted to make a background service for the monitoring part. And I've been reading the Android Developer Guide and the Reference, but still can't fully understand the activity-service-process-lifecycle thing.
Consider this: you start the application. It gets a GPS fix and now you can start monitoring the location updates and save them. When you do so, it should start a service that receives GPS location updates. So now you have an activity AND a service running in the same process. Ok. But what happens if you push the hardware Back-button on your phone? Will only the activity be killed with the process still running your service? Or will it kill both, the activity and the service and thus also the process? Is there some way to ensure the service keeps running in the same process after the activity is killed? But a way not so complicated as the whole aidl开发者_如何转开发 thing for remote processes?
Creating a service in a new process seems unnecessary to me, because no other application should use my service, I just need the monitoring part to keep running while the (GUI) activity is dead. I wanted to make something like the Local Service example on the Developer site, but I must be sure the service keeps running after the activity is killed.
When the user hits the back
button it is different that when the system ends the process that the application was running in. The current activity
will finish()
but the process remains alive. Android will, as long as memory permits it to, keep the service alive regardless of whether or not the activity is visible.
From the docs
If the service has been started, then its hosting process is considered to be less important than any processes that are currently visible to the user on-screen, but more important than any process not visible. Because only a few processes are generally visible to the user, this means that the service should not be killed except in extreme low memory conditions.
Services should NOT however remain in memory forever, this is bad practice and not exactly what you want. I would recommend using an IntentService
coupled to receive location updates via a LocationListener
and LocationManager
link to docs
public void requestLocationUpdates (String provider, long minTime, float minDistance, PendingIntent intent)
This setup should serve you quite well because on each update you can fire off an Intent
which can be handled by your Service
, if it is not alive it will be created.
精彩评论