IntentService

注:
IntentService类在API级别30(Android R?)中被弃用。 IntentService受Android 8.0(API级别26)施加的所有后台执行限制的约束。推荐使用{@link android.support.v4.app.JobIntentService},它在Android 8或更高版本上运行时使用Job而不是Service。

IntentService介绍

IntentService是Service的扩展,可按需处理异步请求(请求一般以intent表示), client端通过调用Context.startService(Intent)发送请求, 然后service将被启动,使用工作线程依次处理intent,当所有intent处理完毕,则停止service

这种“工作队列处理器”模式通常用于为主线程减负,将耗时的可能block主线程的工作放到工作线程去处理。IntentService类的存在是为了简化这种模式。使用IntentService,需要继承IntentService,同时实现onHandleIntent(android.content.Intent)方法。IntentService接收从client端发过来的intent,将其作为消息发给工作线程去处理消息。

所有请求都在一个工作线程上处理——它们可能很耗时(根据需要)(但不会阻塞应用程序的main loop),但一次只处理一个请求。

IntentService代码

定义:

/**
 * 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.
 *
 * <p>This "work queue processor" pattern is commonly used to offload tasks
 * from an application's main thread.  The IntentService class exists to
 * simplify this pattern and take care of the mechanics.  To use it, extend
 * IntentService and implement {@link #onHandleIntent(Intent)}.  IntentService
 * will receive the Intents, launch a worker thread, and stop the service as
 * appropriate.
 *
 * <p>All requests are handled on a single worker thread -- they may take as
 * long as necessary (and will not block the application's main loop), but
 * only one request will be processed at a time.
 *
 * <p class="note"><b>Note:</b> IntentService is subject to all the
 * <a href="/preview/features/background.html">background execution limits</a>
 * imposed with Android 8.0 (API level 26). In most cases, you are better off
 * using {@link android.support.v4.app.JobIntentService}, which uses jobs
 * instead of services when running on Android 8.0 or higher.
 * </p>
 *
 * @see android.support.v4.app.JobIntentService
 * @see android.os.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值