4

Android入门第42天-Android中的Service(IntentService)

 1 year ago
source link: https://blog.csdn.net/lifetragedy/article/details/128175889
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在前一篇中我们讲了bindService的使用。并且我们留下了一个念想,即在bindService取值时故意阻塞30秒,引起了一次ANR并引出了今天的章节-IntentService。

IntentService的生命周期中有一个非常好的方法-onHandleIntent方法,它是一个abstract方法,开发者在实现IntentService时可以覆盖它来处理“长事务”。

IntentService

Android开发者官网说过:

  1. Service不是一个单独的进程,它和它的应用程序在同一个进程中
  2. Service不是一个线程,这样就意味着我们应该避免在Service中进行耗时操作

于是乎,Android给我们提供了解决上述问题的替代品,就是下面要讲的IntentService; IntentService是继承与Service并处理异步请求的一个类,在IntentService中有 一个工作线程来处理耗时操作,请求的Intent记录会加入队列。

这么神奇?

我们来看演示,如何来验证这个IntentService里的onHandleIntent处理这种长事务。

设Service里有一个字符型数组:

   private String[] stdNames = new String[]{"小王", "小明", "小张"};

在Activity里输入数组下标后、等待30秒、然后把相对应的数组下标所对应的StudentName显示在Toast里,看看是不是会发生ANR。

该点击动作可以反复点击,因为每次点击后都会执行unbindService。

c6dbf703c8224decafacbf0c05bba75d.png

代码核心设计

IntentService没什么特殊的,它只是extends 自 IntentService,同时它拥有一个可以被覆盖的:onHandleIntent方法。

  1. 我们这次使用CallBack模式来实现Service里长事务结束后回调activity里的handler实现数值传递;
  2. 我们使用intent.putExtra来实现activity里的数值传递到service中去;

service注册



newCodeMoreWhite.png

 Service类-LongWaitingService



newCodeMoreWhite.png

主类-MainActivity.java



newCodeMoreWhite.png

来看运行效果

看,再也没有ANR了,结果成功通过CALL BACK回传Activity。

因此我们一般都会这么使用IntentService来实现一些资源异步加载、第三方API回调。

f0e14779c1744bb198acfa4db1c3a9da.png

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK