IntentService的踩坑与分析

本文详细分析了IntentService在使用过程中遇到的构造器问题,探讨了为何子类化IntentService时需要手动添加无参构造器,并通过源码解析揭示了IntentService如何通过消息队列执行任务并在完成后自动停止自身。此外,文章还指出框架层的这一设计对开发者体验的影响。
摘要由CSDN通过智能技术生成

IntentService是一个轻量级的执行异步任务的Service,它提供了一种任务队列消费的模式来处理任务,并支持以Intent来传递数据,与此同时,他还会在任务结束后,停止自身,一般用来在Service中执行耗时任务。

使用

我们先看下他怎么使用,看下类注释的说明:

 * IntentService is a base class for {
   @link Service}s that handle asynchronous
 * requests (expressed as {
   @link Intent}s) on demand.  Clients send requests
 * through {
   @link android.content.Context#startService(Intent)} calls; the
 * service is started as needed, handles each Intent in turn using a worker
 * thread, and stops itself when it runs out of work.

很简单,创建IntentService的子类,并实现onHandleIntent方法

public class IntentServiceImpl extends IntentService {
   

  public IntentServiceImpl(String name) {
   
    super(name);
  }

  @Override protected void onHandleIntent(@Nullable Intent intent) {
   
    try {
   
      Thread.sleep(3000);
    } catch (InterruptedException e) {
   
      e.printStackTrace();
    }
  }
}

然后在AndroidManifest.xml中注册服务

<service android:name="com.github.frameworkaly.service.IntentServiceImpl" />

然后就可以按照启动普通服务的方式来启动这个服务了。

Intent intent = new Intent
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值