IntentService是Service类的子类,用来处理异步请求。客户端可以通过startService(Intent)方法传递请求给IntentService。IntentService在onCreate()函数中通过HandlerThread单独开启一个线程来处理所有Intent请求对象(通过startService的方式发送过来的)所对应的任务,这样以免事务处理阻塞主线程。执行完所一个Intent请求对象所对应的工作之后,如果没有新的Intent请求达到,则自动停止Service;否则执行下一个Intent请求所对应的任务。
  IntentService在处理事务时,还是采用的Handler方式,创建一个名叫ServiceHandler的内部Handler,并把它直接绑定到HandlerThread所对应的子线程。 ServiceHandler把处理一个intent所对应的事务都封装到叫做onHandleIntent的虚函数;因此我们直接实现虚函数onHandleIntent,再在里面根据Intent的不同进行不同的事务处理就可以了。
另外,IntentService默认实现了Onbind()方法,返回值为null。
  使用IntentService需要两个步骤:
  1、写构造函数
  2、实现虚函数onHandleIntent,并在里面根据Intent的不同进行不同的事务处理就可以了。
好处:处理异步请求的时候可以减少写代码的工作量,比较轻松地实现项目的需求
注意:IntentService的构造函数一定是参数为空的构造函数,然后再在其中调用super("name")这种形式的构造函数。
因为Service的实例化是系统来完成的,而且系统是用参数为空的构造函数来实例化Service的
关于Handler和Service的更多知识请阅读《Looper和Handler》,《关于Handler技术》,《Service简介》,《AIDL和Service实现两进程通信
 
Public Constructors
  IntentService(String name)

Creates an IntentService.
Public Methods
IBinder onBind(Intent intent)

Unless you provide binding for your service, you don't need to implement this method, because the default implementation returns null.
void onCreate()

Called by the system when the service is first created.
void onDestroy()

Called by the system to notify a Service that it is no longer used and is being removed.
void onStart(Intent intent, int startId)

This method is deprecated. Implement onStartCommand(Intent, int, int) instead.
int onStartCommand(Intent intent, int flags, int startId)

You should not override this method for your IntentService.
void setIntentRedelivery(boolean enabled)

Sets intent redelivery preferences.

If enabled is true, onStartCommand(Intent, int, int) will return START_REDELIVER_INTENT, so if this process dies before onHandleIntent(Intent)returns, the process will be restarted and the intent redelivered.

If multiple Intents have been sent, only the most recent one is guaranteed to be redelivered.

If enabled is false (the default), onStartCommand(Intent, int, int) will return START_NOT_STICKY, and if the process dies, the Intent dies along with it.

设置为true时,onStartCommand返回START_REDELIVER_INTENT,否则返回START_NOT_STICKY
关于此的更多内容请参考《Service简介
Protected Methods
abstract void onHandleIntent(Intent intent)

This method is invoked on the worker thread with a request to process.
This method is invoked on the worker thread with a request to process. Only one Intent is processed at a time, but the processing happens on a worker thread that runs independently from other application logic.
So, if this code takes a long time, it will hold up other requests to the same IntentService, but it will not hold up anything else. When all requests have been handled, the IntentService stops itself, so you should not call stopSelf().
该函数用于针对Intent的不同进行不同的事务处理就可以了.执行完所一个Intent请求对象所对应的工作之后,如果没有新的Intent请求达到,
则自动停止Service;否则ServiceHandler会取得下一个Intent请求传人该函数来处理其所对应的任务。
 

实例1
MyIntentService.java文件
package com.lenovo.robin.test;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log; public class MyIntentService extends IntentService {
final static String TAG="robin";
public MyIntentService() {
super("com.lenovo.robin.test.MyIntentService");
Log.i(TAG,this+" is constructed");
}
@Override
protected void onHandleIntent(Intent arg0) {
Log.i(TAG,"begin onHandleIntent() in "+this);
try {
Thread.sleep(10*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG,"end onHandleIntent() in "+this);
}
public void onDestroy()
{
super.onDestroy();
Log.i(TAG,this+" is destroy");
}
}
启动MyIntentServic的代码片段
Intent intent=new Intent(this,MyIntentService.class);
startService(intent);
startService(intent);
startService(intent);
AndroidManifest.xml文件代码片段

<service android:name=".MyIntentService" />

运行结果
09-14 22:23:34.730: I/robin(30943): com.lenovo.robin.test.MyIntentService@40541370 is constructed
09-14 22:23:34.730: I/robin(30943): begin onHandleIntent() in com.lenovo.robin.test.MyIntentService@40541370
09-14 22:23:44.730: I/robin(30943): end onHandleIntent() in com.lenovo.robin.test.MyIntentService@40541370
09-14 22:23:44.730: I/robin(30943): begin onHandleIntent() in com.lenovo.robin.test.MyIntentService@40541370
09-14 22:23:54.740: I/robin(30943): end onHandleIntent() in com.lenovo.robin.test.MyIntentService@40541370
09-14 22:23:54.740: I/robin(30943): begin onHandleIntent() in com.lenovo.robin.test.MyIntentService@40541370
09-14 22:24:04.739: I/robin(30943): end onHandleIntent() in com.lenovo.robin.test.MyIntentService@40541370
09-14 22:24:04.739: I/robin(30943): com.lenovo.robin.test.MyIntentService@40541370 is destroy
 
IntentService源码
package android.app;

import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message; public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery; private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
} @Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
} public IntentService(String name) {
super();
mName = name;
} public void setIntentRedelivery(boolean enabled) {
mRedelivery = enabled;
} @Override
public void onCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock. super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start(); mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
} @Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
} /**
* You should not override this method for your IntentService. Instead,
* override {@link #onHandleIntent}, which the system calls when the IntentService
* receives a start request.
* @see android.app.Service#onStartCommand
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
} @Override
public void onDestroy() {
mServiceLooper.quit();
}
@Override
public IBinder onBind(Intent intent) {
return null;
} protected abstract void onHandleIntent(Intent intent);
}

IntentService简介的更多相关文章

  1. Android IntentService的使用和源码分析

    引言 Service服务是Android四大组件之一,在Android中有着举足重轻的作用.Service服务是工作的UI线程中,当你的应用需要下载一个文件或者播放音乐等长期处于后台工作而有没有UI界 ...

  2. Android 进阶16:IntentService 使用及源码解析

    It's time to start living the life you've only imagined. 读完本文你将了解: IntentService 简介 IntentService 源码 ...

  3. 什么是IntentService?有何优点?

    一.IntentService 简介 IntentService 是 Service 的子类,比普通的 Service 增加了额外的功能.先看 Service 本身存在两个问题:Service 不会专 ...

  4. Android 面试题--Service

    1.Service 是否在 main thread 中执行, service 里面是否能执行耗时的操作?默认情况,如果没有显示的指 servic 所运行的进程, Service 和 activity ...

  5. Android消息队列和Looper

    1. 什么是消息队列 消息队列在android中对应MessageQueue这个类,顾名思义,消息队列中存放了大量的消息(Message) 2.什么是消息 消息(Message)代表一个行为(what ...

  6. Andorid面试问题整理

    Acitivty的四中启动模式与特点. standard:默认的启动模式 singleTop:适合那种接受通知启动的页面,比如新闻客户端之类的,可能会给你推送好几次 ,但是每次都是打开同一张页面调用o ...

  7. Android源码分析-消息队列和Looper

    转载请注明出处:http://blog.csdn.net/singwhatiwanna/article/details/17361775 前言 上周对Android中的事件派发机制进行了分析,这次博主 ...

  8. 【Android】面试宝典

    Android面试 1. 内容介绍................................................................................... ...

  9. Android的线程和线程池

    ---恢复内容开始--- 一.Android线程的形态 (一)AsyncTask解析 AysncTask简介:①.实现上封装了Thread和Handler   ②.不适合进行特别耗时的后台任务 Ays ...

随机推荐

  1. mysql 操作突然断网,MySQL: “lock wait timeout exceeded”

    show processlist;//显示所有进程select * from information_schema.innodb_trx;//查询锁的进程-- kill 310;//杀掉锁进程

  2. 2015GitWebRTC编译实录6

    2015.07.20 libbitrate_controller 编译通过依赖system_wrappers lib,编写测试代码时需要注意.[425/1600 ] CXX obj /webrtc/m ...

  3. Codeforces Round #132 (Div. 2)

    A. Bicycle Chain 统计\(\frac{b_j}{a_i}\)最大值以及个数. B. Olympic Medal \(\frac{m_{out}=\pi (r_1^2-r_2^2)hp_ ...

  4. google-http-java-client(android学习篇2源码)

    package com.google.api.services.samples.googleplus.cmdline.simple;   import com.google.api.client.ht ...

  5. 嵌入式Linux C笔试题积累(转)

    http://blog.csdn.net/h_armony/article/details/6764811 1.   嵌入式系统中断服务子程序(ISR) 中断是嵌入式系统中重要的组成部分,这导致了很 ...

  6. 自我提升mysql

    1.某字段更新 自增 1 update table set a=a+1 2.修改某一字段的数据类型 alter table "tablename" modify  "co ...

  7. 动态链接库中函数的地址确定---PLT和GOT [转]

    前面写过动态链接库 延迟绑定的一篇博文,那篇文章我非常喜欢,但是当时刚搞清楚,自己写的比较凌乱,我最近学习了Ulrich Drepper的How to write share library,学习了几 ...

  8. ORA-12547:TNS:lost contact 问题分析思路

    ORA-12547:TNS:lost contact sqlplus无法正常登陆数据库 解决思路如下: 1.查看操作系统内核参数是否无误 [oracle@normal adump]$ ulimit - ...

  9. 非对称SVD电影推荐系统

    采用1M MovieLensz数据(80%train, 20%test, UserIDs range between 1 and 6040 ,MovieIDs range between 1 and ...

  10. C#代码:用事件模式实现通知

    事件提供了一种标准的机制来通知监听者..NET的事件模式使用了事件语法来实现观察者模式.任意数量的客户对象都可以将自己的处理函数注册到事件上,然后处理这些事件.这些客户对象不需要再编译期就给出.时间也 ...