天天看点

本地Service

通过在content(如activity)中调用startService(Intent )启动service,service只有在调用stopSelf(),或者另外component调用stopService()时才会停止。

service启动时会自动调用

Service类:

This is the base class for all services. When you extend this class, it's important that you create a new thread in which to do all the service's work, because the service uses your application's main thread, by default, which could slow the performance of any activity your application is running

IntentService类:

This is a subclass of <code>Service</code> that uses a worker thread to handle all start requests, one at a time. This is the best option if you don't require that your service handle multiple requests simultaneously. All you need to do is implement <code>onHandleIntent()</code>, which receives the intent for each start request so you can do the background work.

IntentService类做如下工作:

Creates a default worker thread that executes all intents delivered to <code>onStartCommand()</code> separate from your application's main thread.

Creates a work queue that passes one intent at a time to your <code>onHandleIntent()</code> implementation, so you never have to worry about multi-threading.

Stops the service after all start requests have been handled, so you never have to call <code>stopSelf()</code>.

Provides default implementation of <code>onBind()</code> that returns null.

Provides a default implementation of <code>onStartCommand()</code> that sends the intent to the work queue and then to your <code>onHandleIntent()</code> implementation

所以,只需实现onHandleIntent()函数,和构造函数,不比考虑多线程的问题

当重载其他回调函数时,记住super

继续阅读