Service学习笔记 - m1688/Hirebird GitHub Wiki
I like to divide Services into two different types. First is the one that performs work for the application independent of the user’s input.The other type of Service is one that’s directly triggered by an action from the user—for example, a photo-sharing application.
Starting Services A Service can be started in two ways: Either it receives an Intent through the Context.startService() method, or a client (either local or remote) binds to it using the Context.bindService() method. Both of these methods will result in the Service moving to the “started” state.
When you start a Service using Context.startService(), the onStartCommand() callback is triggered on your Service.
START_STICKY, START_NOT_STICKY, and START_REDELIVER_INTENT.
Because using Context.startService() can be considered as asynchronous (see Figure 6-1), you may also need a way to signal back to the Activity that your operation is complete. One way of doing so is to use a programmatic BroadcastReceiver
If you need to keep your Service in the foreground even if your application is not the active one, you can do so by calling the method Service.startForeground()
If your Service started from Context.bindService(), it will be automatically stopped when the last client disconnects (that is, called Context.unbindService()).
Service can be running when your application isn’t in the foreground, but this doesn’t mean that it won’t be executing any work on the main thread. Because all components’ lifecycle callbacks are executed on the application’s main thread, you need to make sure that any long-running operation you perform in your Service is moved to a new thread.
If you send five Intents to an IntentService, they will be executed in sequential order, one at a time.
you can set up an AsyncTask to use an Executor for spawning instances in parallel. However, because AsyncTask is designed for operations running only a few seconds at most, you may need to do some more work if your operations are running for a significant amount of time.
he IntentService example shown earlier in this chapter provides an easy-to-use one-way communication between a component (usually an Activity) and the Service. But usually you want know the result of the operation you start, so you need some way for the Service to report back once it completes its task. You can do so several ways, but if you want to maintain the asynchronous behavior of the IntentService, the best approach is to send a broadcast, which is just as simple as starting an operation in your IntentService. You just need to implement a BroadcastReceiver that listens for the response.