The difference between Bindservice and StartService

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.