IntentService使用详解和实例介绍
来源:互联网 发布:Linux修改进程名字 编辑:程序博客网 时间:2024/06/08 03:14
IntentService定义
IntentService继承与Service,用来处理异步请求。客户端可以通过startService(Intent)方法传递请求给IntentService。IntentService在onCreate()函数中通过HandlerThread单独开启一个线程来依次处理所有Intent请求对象所对应的任务。
这样以免事务处理阻塞主线程(ANR)。执行完所一个Intent请求对象所对应的工作之后,如果没有新的Intent请求达到,则**自动停止**Service;否则执行下一个Intent请求所对应的任务。
IntentService在处理事务时,还是采用的Handler方式,创建一个名叫ServiceHandler的内部Handler,并把它直接绑定到HandlerThread所对应的子线程。 ServiceHandler把处理一个intent所对应的事务都封装到叫做onHandleIntent的虚函数;因此我们直接实现虚函数onHandleIntent,再在里面根据Intent的不同进行不同的事务处理就可以了。
另外,IntentService默认实现了Onbind()方法,返回值为null。
使用IntentService需要实现的两个方法:
构造函数
IntentService的构造函数一定是参数为空的构造函数,然后再在其中调用super(“name”)这种形式的构造函数。因为Service的实例化是系统来完成的,而且系统是用参数为空的构造函数来实例化Service的
实现虚函数onHandleIntent
在里面根据Intent的不同进行不同的事务处理。
好处:处理异步请求的时候可以减少写代码的工作量,比较轻松地实现项目的需求。
IntentService与Service的区别
Service不是独立的进程,也不是独立的线程,它是依赖于应用程序的主线程的,不建议在Service中编写耗时的逻辑和操作,否则会引起ANR。
IntentService 它创建了一个独立的工作线程来处理所有的通过onStartCommand()传递给服务的intents(把intent插入到工作队列中)。通过工作队列把intent逐个发送给onHandleIntent()。
不需要主动调用stopSelft()来结束服务。因为,在所有的intent被处理完后,系统会自动关闭服务。
默认实现的onBind()返回null。
IntentService实例介绍
首先是myIntentService.java
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
然后记得在Manifest.xml中注册服务
- 1
- 2
- 3
- 4
- 5
最后在Activity中开启服务
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
运行结果:
IntentService在onCreate()函数中通过HandlerThread单独开启一个线程来依次处理所有Intent请求对象所对应的任务。
通过onStartCommand()传递给服务intent被依次插入到工作队列中。工作队列又把intent逐个发送给onHandleIntent()。
注意:
它只有一个工作线程,名字就是构造函数的那个字符串,也就是“myIntentService”,我们知道多次开启service,只会调用一次onCreate方法(创建一个工作线程),多次onStartCommand方法(用于传入intent通过工作队列再发给onHandleIntent函数做处理)。
- IntentService使用详解和实例介绍
- IntentService使用详解和实例介绍
- IntentService使用详解和实例介绍
- IntentService初步应用和实例介绍
- 一个IntentService使用实例
- IntentService介绍及使用
- IntentService的使用介绍
- IntentService使用详解
- IntentService原理和使用
- Android service和IntentService使用
- IntentService介绍
- IntentService介绍
- IntentService 详解(从使用到源码撸一遍)
- IntentService 详解
- IntentService 详解
- IntentService详解
- IntentService详解
- intentservice详解
- jzoj【NOIP2017提高A组冲刺11.3】高考是不可能高考的
- Python生成随机数的方法
- 关于@Value注解,注意事项
- MySQL之存储引擎
- Visual Studio 2017 无法引用 windows.h wincon.h 的解决办法
- IntentService使用详解和实例介绍
- ZOJ
- 随机数的方法
- ANR分析-WaitingPerformingGc
- Android N指纹识别
- 算法问题
- 《正义之心-为什么人们总是相信我对你错》-读后感
- if break、if continue和if return三者之间的区别
- 【机器学习实战】第12章 使用FP-growth算法来高效发现频繁项集