Many netizens may find that there is an IntentService in addition to the Service in Android. What are the differences between them? In terms of inheritance relationships, IntentService is a subclass of Service. The internal implementation Code involves logoff that Android beginners do not know. Android123 has explained their usage in earlier articles, I will not go into details here. You can refer to the source code implementation as follows:
Copy codeThe Code is as follows: public abstract class IntentService extends Service {
Private volatile low.mserviceloaders;
Private volatile ServiceHandler mServiceHandler; // a Handler encapsulates the logoff object
Private String mName;
Private boolean mRedelivery;
Private final class ServiceHandler extends Handler {
Public ServiceHandler (low.logoff ){
Super (logoff );
}
@ Override
Public void handleMessage (Message msg ){
OnHandleIntent (Intent) msg. obj );
StopSelf (msg. arg1 );
}
}
Public IntentService (String name) {// constructor. A name must be provided as the identifier.
Super ();
MName = name;
}
If the following setIntentRedelivery parameter is trueCopy codeThe Code is as follows: onStartCommand (Intent, int, int)} will return
Service # START_REDELIVER_INTENT}, so if this process dies before
OnHandleIntent (Intent)} returns, the process will be restarted
If it is falseCopy codeThe Code is as follows: 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 () {// override the creation of the parent class Service here, mainly to construct a thread
Super. onCreate ();
HandlerThread thread = new HandlerThread ("IntentService [" + mName + "]");
Thread. start ();
Mserviceloaders = thread. getLooper ();
MServiceHandler = new ServiceHandler (mserviceloader );
}
@ Override
Public void onStart (Intent intent, int startId) {// Service Startup parameter control before Android 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) {// service startup parameters after Android 2.0
OnStart (intent, startId );
Return mRedelivery? START_REDELIVER_INTENT: START_NOT_STICKY;
}
@ Override
Public void onDestroy () {// when the service is destroyed, the logoff must be released, which is very important.
Mserviceloading. quit ();
}
@ Override
Public IBinder onBind (Intent intent ){
Return null;
}
Protected abstract void onHandleIntent (Intent intent );
}
From the code above, we can see that IntentService and Service are different. We can solve the Logic Blocking problem in standard Service through logoff and Thread. After all, Android Service will also be blocked.