A common application scenario:
On the loginactivity login page, click login and send it to the background service CmdSocketService to process the login service,
And get the login status (feedback on successful failures)
LoginActivity uses the encapsulated cmdetservice (service) class method:
A) defined in the loginActivity class:
CmdSocketService serviceBinder;
// The following is the processing function used to connect to the CmdSocketService.
Private ServiceConnection mConn = newServiceConnection ()
{
Public void onServiceConnected (ComponentName className, IBinder service)
{
// Here, the service is actually a MyBinder Class Object, where a getService () method is used to return the service object itself.
// LoginActivity obtains the reference of the service object (serviceBinder). The Chinese method of using the service is the same as that of common class methods.
ServiceBinder = (CmdSocketService. MyBinder) service). getService ();
Log. v (TAG, "get Started socketservice reference OK! ");
MBound = true; // whether the Custom Service is bound with a tag
}
Public void onServiceDisconnected (ComponentName className ){
ServiceBinder = null;
MBound = false;
}
};
B) defined in onStart:
Intent intent = new Intent (this, CmdSocketService. class)
BindService (intent, mConn, Context. BIND_AUTO_CREATE );
// ================================================ ==================================
Service class definition:
Public class extends socketservice extends Service {
// 1.
Public class MyBinder extends Binder
{
Public synchronized socketservice getService ()
{
Log. v (TAG, "getService ()");
Return cmdetservice. this; // return the service object itself
}
}
// 2.
Private MyBinder mBinder = new MyBinder ();
// 3. Feedback to onServiceConnection ()
Implementation in onBind:
{
Return mBinder;
}
Activity and services binding process: (bindService Mode)
1. new intent specifies which service to bind
2. Start binding and pass the service connection processing function ServiceConnection () (a bit like a callback function). // when calling this function, android will call the onBind () function in the service class.
3. The onBind () function returns a Binder subclass object. The Binder subclass has a getServices () method, which returns the service object itself ., In the end, loginActiviy returns a reference to the service object.
4. After the logingActivity and service are successfully bound. Android calls the onServiceConnected () function. In this function, IBinder is the subclass object MyBinder returned by the service.
5. Call the method getService () in MyBinder to obtain the reference of the service object.
6. Start to call the public methods in the service.