Android Service
Please explain an Android Service
. How开发者_开发技巧 does it differ from an Activity
? Does it depend on an application state such as running in the foreground/background?
From the Android Developer's SDK reference for Service:
A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.
It is very important to note
that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work.
This is in contrast to an activity which is best understood as something a user directly sees and interacts with (a UI.)
A service, as mentioned above, can be used for longer-running operations that will continue even if you have no foreground activity, but they can, and eventually will be killed by Android's lifecycle if left in the "background" state. If you need your service to continue running as a single instance without being killed and restarted, I would recommend placing startForeground(int id, Notification notification) in your Service's onCreate
method and stopForeground(boolean removeNotification) in your Service's onDestroy
method.
For example, I have an app that uses a foreground Service
to record accelerometer data all night while the android device is next to the user's body. Though it is not required to be active, I also have an Activity
that broadcast an Intent
to a BroadcastReceiver
inside the Service
which tells the Service
that it should also broadcast an Intent
with accelerometer data as extras to a BroadcastReceiver
inside the Activity
.
Code: SleepActivity SleepAccelerometerService
Good luck and let me know if you need any more information!
a Service is a context similar to Activity but has no GUI.
Important: A service doesn't run in a new thread!
Read about Service and also check out How to always run a service in the background?
精彩评论