继承Service,启动肯定也是startService
Intent intent=new Intent(this,Task.class);
startService(intent);
执行后,会调起service,service中的:onStartCommand将会调用;即:
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
继续执行:onStart(intent, startId);
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
这里将intent传到handler中:
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);
}
}
则调用handleMessage中的onHandleIntent((Intent)msg.obj);和stopSelf(msg.arg1)(停止自身service);
@WorkerThread
protected abstract void onHandleIntent(@Nullable Intent intent);
抽象方法,凡是继承intentservice的类,都要实现该方法,如下:
public class Task extends IntentService {
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public Task(String name) {
super(name);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
}
}
即,在startService之后,会调用onHandleIntent方法,