Difference:
StartService, shutdown service exit Activity,service still running in the background
Bindservice, close service quit activity Direct StopService, stop service
Bindservice is used to bind a service, communicate with the service, StartService to start the stop service
General process of Bindservice mode:
① New service class Bindservice. Create a new inner class Mybinder in the Bindservice class, inheriting from Binder (Binder implements IBinder interface). Mybinder provides methods to return Bindservice instances.
public class Mybinder extends binder{
Public Bindservice GetService () {
return bindservice.this;
}
}
Instantiate Mybinder get Mybinder object;
Override the Onbind () method:
@Override
Public IBinder Onbind (Intent Intent) {
return mybinder;
}
② in activity, instantiate the implementation class of the Serviceconnection interface, overriding the Onserviceconnected () and onservicedisconnected () methods
Serviceconnection conn=new serviceconnection () {
@Override
public void onserviceconnected (componentname name, IBinder service) {
}
@Override
public void onservicedisconnected (componentname name) {
}
};
③ in the activity's OnCreate () method, create a new intent, and bind the service
Intent intent=new Intent (mainactivity.this,bindservice.class);
Bindservice (Intent, conn,bind_auto_create);
④ in the OnDestroy of activity, add
Unbindservice (conn);
If this step is not added, it will be reported android.app.ServiceConnectionLeaked: ******. Mainactivity has leaked serviceconnection exception.
Bindservice () is executed as follows:
Bindservice (Intent,conn,flag)->service:oncreate ()->service:onbind ()->activity:onserviceconnected ()
The difference between Bindservice and StartService