IntentService,你了解的多少?

2016-04-25 20:43 评论 0 条

一、摘要

由于大多数被启动的services不需要同时处理多个请求,实际上是不安全的,最好的选择使用IntentService实现Service类,IntentService执行以下几个操作:

  • 独立于UI thread创建一个默认的worker thread来处理所有发送到onStartCommand()的intents
  • 创建一个worker queue在某个时间传递一个intent到onHandleIntent()实现方法,所以你不要担心多线程的问题
  • 在所有启动的请求被处理后,停止服务,因此,你不用调用stopSelf()方法
  • 默认情况下,onBind()实现方法返回null
  • 默认情况下,onStartCommand()实现方法发送intent到work queue,然后传递到onHandleIntent()实现方法

二、必须重写的两个方法

所有的事实说明,你需要实现onHandleIntent()方法来处理客户端指定处理的工作,因此,需要重写父类的构造方法,代码如下:

  1. /**独立于UI线程创建一个worker thread来处理发送到onStartCommand()方法的intents 
  2.  * Created by Administrator on 2016/4/25. 
  3.  */  
  4. public class SubIntentService extends android.app.IntentService {  
  5.     /** 
  6.      * 该构造方法是必须的,而且必须重写父类的IntentService(String)方法 
  7.      */  
  8.     public SubIntentService() {  
  9.         super("SubIntentService");  
  10.     }  
  11.     /** 
  12.      * The IntentService calls this method from the default worker thread with 
  13.      * the intent that started the service. When this method returns, IntentService 
  14.      * stops the service, as appropriate. 
  15.      */  
  16.     @Override  
  17.     protected void onHandleIntent(Intent intent) {  
  18.   
  19.     }  
  20.   
  21. }  

这个两个方法是必须:一、重写父类的构造方法super(String);二、重写onHandleIntent(Intent)。

三、重写额外的方法

如果想要重写其他的回调方法,比如:onCreate()onStartCommand()onDestroy(),必须保证回调super实现方法,以便IntentService()可以恰当处理work thread生命周期,代码如下:

  1. @Override  
  2. public int onStartCommand(Intent intent, int flags, int startId) {  
  3.     Toast.makeText(this"service starting", Toast.LENGTH_SHORT).show();  
  4.     return super.onStartCommand(intent,flags,startId);  
  5. }  

除了onHandleIntent()不需要调用super实现方法外,onBind()是另外一个同样不需要调用super关键字的方法

当前文章价值8.62元,扫一扫支付后添加微信提供帮助!(如不能解决您的问题,可以申请退款)

你可能感兴趣的文章

来源:每日教程每日一例,深入学习实用技术教程,关注公众号TeachCourse
转载请注明出处: https://www.teachcourse.cn/1701.html ,谢谢支持!

资源分享

Andorid开发之反编译工具apktool学习 Andorid开发之反编译工具apktoo
harmony学习UIAbility生命周期 harmony学习UIAbility生命周期
Android开发之ProgressDialog读取文件进度解析 Android开发之ProgressDialog
python字符串格式化的方式 python字符串格式化的方式