代码如下:
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler; //一个Handler封装了Looper对象
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) { //构造方法,需要提供一个name作为标识
super();
mName = name;
}
对于下面的setIntentRedelivery的参数,如果为真时
代码如下:
onStartCommand(Intent, int, int)} will return
Service#START_REDELIVER_INTENT}, so if this process dies before
onHandleIntent(Intent)} returns, the process will be restarted
如果为假时
代码如下:
onStartCommand(Intent, int, int)} will return
Service#START_NOT_STICKY}, and if the process dies
public void setIntentRedelivery(boolean enabled) {
mRedelivery = enabled;
}
@Override
public void onCreate() { //这里重写父类Service的创建,主要是构造一个线程
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) { //Android 2.0以前的Service启动参数控制
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) { //Android 2.0以后的服务启动参数
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onDestroy() { //服务摧毁的时候Looper一定要释放掉,这点很重要。
mServiceLooper.quit();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
protected abstract void onHandleIntent(Intent intent);
}
从上面的代码相信大家可以看出IntentService和Service的不同了,通过Looper和Thread来解决标准Service中处理逻辑的阻塞问题,毕竟Android的Service也是会阻塞的。 您可能感兴趣的文章:Android编程实现自定义分享列表ACTION_SEND功能的方法Android使用Intent.ACTION_SEND分享图片和文字内容的示例代码