创建一个开始的服务:
一个开始的服务被启动当另一个组件通过调用startService()。然后这个服务调用onStartCommand()方法。当一个服务被启动了,它的是独立于启动它的组件的。这个服务将一直运行于后台,甚至启动它的组件被销毁。同样的,这个服务能停止他自己当它的任务完成,通过调用stopSelf()。或者另一些组件也能停止它,通过调用 stopService()。
一个应用组件比如一个activity能开始一个服务通过调用 startService(),通过Intent去指定这个服务包括传递的数据。这个服务将会接受到Intent在 onStartCommand()方法里。
例如,假如一个activity需要保存一些数据到在线数据库中,这个activity能开始一个服务,传递它的数据去保存通过Intent的 startService()方法。这个服务接受到这个Intent在 onStartCommand()方法中,然后连接到Intent,执行数据库的保存事务。当这个任务做完,这个服务将自动被销毁。
传统上,你能基础两个类去创建一个开始的服务。
Service
这是一个基础的services类,当你继承这个类,非常重要的是你创建一个新的线程去做所有的service的工作。因为这个service是再你的主 线程中的,默认情况下,你的应用程序运行的会比较慢的。所以非常有必要在service中创建一个新的线程去执行service的任务。
IntentService
这是一个service的子类,使用一个工作的线程去处理所以的开始请求,每次一个。这是一个最好的选择如果你不要求你的服务同时处理多个请求。你必须去实现 onHandleIntent()方法,这个方法是去接受每一个Intent的请求,因此你可以做后台的工作。
继承IntentService类
因为许多开启的服务不需要去同时执行多个请求,所以它可能是最好的如果你实现你的service用IntentService类。
这而是一个实现了IntentService得例子:
public class HelloIntentService extends IntentService {
/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public HelloIntentService() {
super("HelloIntentService");
}
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
@Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
long endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
}
}
上面的构造器和 onHandleIntent()方法是必须得。