Many netizens may find that there is a intentservice in addition to the service in Android, what is the difference between them? In terms of inheritance, Intentservice is a subclass of service, and the internally implemented code involves some of the Android starter developers who don't understand the looper,android123 that were used in earlier articles, no longer repeating, About the principle you can see the source code to achieve the following:
Copy Code code as follows:
Public abstract class Intentservice extends Service {
private volatile looper mservicelooper;
private volatile Servicehandler Mservicehandler; A handler encapsulates the Looper object
Private String Mname;
Private Boolean mredelivery;
Private Final class Servicehandler extends Handler {
Public Servicehandler (Looper looper) {
Super (Looper);
}
@Override
public void Handlemessage (msg) {
Onhandleintent ((Intent) msg.obj);
Stopself (MSG.ARG1);
}
}
Public Intentservice (String name) {//constructor method, need to provide a name as identity
Super ();
Mname = name;
}
For the following arguments for the setintentredelivery, if True
Copy Code code as follows:
Onstartcommand (Intent, int, int)} 'll return
Service#start_redeliver_intent}, so if this process dies before
Onhandleintent (Intent)} returns, the process would be restarted
If the time is false
Copy Code code as follows:
Onstartcommand (Intent, int, int)} 'll return
Service#start_not_sticky}, and if the process dies
public void Setintentredelivery (Boolean enabled) {
Mredelivery = enabled;
}
@Override
public void OnCreate () {///rewrite the creation of the parent service, primarily to construct a thread
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 service startup parameter control prior to 2.0
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 service startup Parameters
OnStart (Intent, Startid);
Return mredelivery? Start_redeliver_intent:start_not_sticky;
}
@Override
public void OnDestroy () {//Looper must be released when the service is destroyed, this is important.
Mservicelooper.quit ();
}
@Override
Public IBinder Onbind (Intent Intent) {
return null;
}
protected abstract void Onhandleintent (Intent Intent);
}
From the above code I believe you can see that intentservice and service are different, through looper and thread to solve the problem of handling logic in standard service, after all, Android service is blocked.