Android Service---继承IntentService类

来源:互联网 发布:api接口怎么用java 编辑:程序博客网 时间:2024/04/29 13:55
因为大多被启动类型的服务不需要同时处理多个请求(这实际是一个危险的多线程场景),因此使用IntentService类来实现自己的服务可能是最好的。

IntentService类执行以下操作:

1.  创建一个独立与应用程序主线程的默认工作线程,执行所有的给onStartCommand()方法Intent的处理;

2.  创建一个工作队列,以便每次只给你的onHandleIntent()方法实现传递一个Intent,因此你不必担心多线程的问题;

3.  所有的启动请求都被处理之后终止这个服务,因此你不需要自己去调用stopSelf()方法;

4.  提供返回null的onBind()方法的默认实现;

5.  提供一个给工作队列发送Intent对象的onStartCommand()方法的默认实现和onHandleIntent()方法的实现。

所以这些加起来实际上只需要实现onHandleIntent()方法,来完成由客户提供的工作(虽然,你还需要给服务提供一个小的构造器)。

例如:

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()方法的实现。

如果你还决定要重写其他的回调方法,如onCreate()、onStartCommand()、或onDestroy(),那么就要确保调用父类的实现,以便IntentService对象能够适当的处理工作线程的活动。

例如,onStartCommand()方法必须返回默认的实现(默认的实现获取Intent并把它交付给onHandleIntent()方法):

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
    return super.onStartCommand(intent,flags,startId);
}

除了onHandleIntent()方法以外,唯一不需要调用实现的方法是onBind()方法(但是如果你的服务允许绑定,就要实现这个方法)。

原创粉丝点击