IntentService

IntentService

   IntentService是Service的一个子类,在收到开始请求时会立马开启一个工作线程。如果你的Service不需要同时处理多请求,那么你可以选择使用它。你需要实现onHandleIntent()方法,当它收到开始请求时,它就会在后台开始工作。

IntentService好处

1.创建一个默认的工作线程处理所有的Intent传递给onStartCommon()方法,与应用的主线程分离。

2.创建一个工作队列,每次传递一个Intent给你的onHandleIntent()实现方法。这样当你有多个运行的线程时不会混乱。

3.当所有的请求处理完时它会自己停止,不需要调用stopSelf();

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

5.提供默认的onStartCommon方法,它会发送Intent到工作队列,然后再将Intent传递给你实现的onHandlerIntent方法。

简单例子

public class HelloIntentService extends IntentService {
  public HelloIntentService() {
      super("HelloIntentService");
  }

  @Override
  protected voidonHandleIntent(Intent intent) {
      // Normally we would do some work here, likedownload 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) {
              }
          }
      }
  }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值