1 Service和IntentService的区别
-
Service是运行在主线程,不能在Service进行耗时操作否则会有ANR;IntentService内部开启了一个线程,可以执行耗时操作
-
Service需要手动关闭服务;IntentService在执行完成后会自动关闭服务
-
IntentService继承自Service,拥有和Service相同的生命周期
2 IntentService详解
IntentService特点:
-
它创建了一个独立的工作线程来处理所有的通过
onStartCommand()
传递给服务的Intent -
创建了一个工作队列,来逐个发送Intent给
onHandleIntent()
-
不需要主动调用
stopSelf()
结束服务。在所有的Intent被处理完后,系统会自动关闭服务 -
默认实现的
onBind()
返回null -
默认实现的
onStartCommand()
的目的是将Intent插入到工作队列中
继承IntentService需要实现两个函数:构造函数和 onHandleIntent()
函数。
注意:要覆盖IntentService的其他函数时,要通过super调用父类的对应的函数。
IntentService源码概括:
调用 onCreate()
时创建HandlerThread -> 调用 onStart(Intent inent, int startId)
时发送Intent -> onStartCommand(Intent intent, int flags, int startId)
时内部调用了 onStart()
将接收到的Intent发送 -> Handler的 handleMessage()
调用 onHandleIntent(intent)
提供给子类,通过startId作为停止服务标志 stopSelf(startId)
IntentService源码:
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
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() {
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);
}
@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);
}