2.APP Components-services/bound Services

Source: Internet
Author: User

1. Bound Services

A bound service is the server in a Client-server interface. A bound service allows (such as activities) to bind to the service, send

Requests, receive responses, and even perform interprocess communication (IPC). A bound service typically lives only while it serves

Another application component and does not run in the background indefinitely

2. The Basics

A Bound Service is an implementation of the Services class then allows other applications to bind to it and interact with it. To provide binding

For a service, you must implement the Onbind () callback method. This method returns a IBinder object that defines the programming

Interface that clients can use to interact with the service.

3. Creating a Bound Service

When creating a service is provides binding, you must provide IBinder An that provides the programming interface That clients can use to

Interact with the service. There is three ways you can define the interface:

<1>extending the Binder class

<2>using a Messenger

<3>using Aidl

4. Extending the Binder class

If your service is private to your own application and runs in the same process as the client ( which is common), you should create your

interface by extending the Binder class and returning a instance of it from onBind() . The client receives the and Binder can use it to

Directly access public methods available in either the Binder implementation or even the Service .

This was the preferred technique when your service was merely a background worker for your own application. The only reason your would not

Create your interface this to is because your service are used by other applications or across separate proce SSEs.

//Activity_bingding.xml<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"Xmlns:tools="Http://schemas.android.com/tools"Android:layout_width="match_parent"Android:layout_height="match_parent"Tools:context="mirror.android.extendingbinder.BindingActivity"> <Button Android:id="@+id/btn_create_service"Android:layout_width="wrap_content"Android:layout_height="wrap_content"Android:text="Create Service"/></relativelayout>
//Localservice.classPackage Mirror.android.extendingbinder;import Java.util.random;import android.app.service;import Android.content.intent;import Android.os.binder;import Android.os.IBinder; Public classLocalService extends Service {PrivateFinal IBinder Mbinder =NewLocalbinder (); PrivateFinal Random Mgenerator =NewRandom (); /*1.In your service, create an instance of binders that either: * <1> contains public methods that the CLI ENT can call * <2> returns the current Service instance, which have public methods the client can call * &L T;3> or, returns an instance of another class hosted by the service with public methods the client can call*/     Public classLocalbinder extends binder{LocalService getService () {returnLocalService. This; }    }         /*2.Return This instance of binders from the Onbind () callback method. */@Override Publicibinder onbind (Intent Intent) {//TODO auto-generated Method Stub        returnMbinder; }        /*The Localbinder provides the GetService () method for clients to retrieve the current instance of LocalService.      *this allows clients to call public methods in the service. *for example, clients can call GetRandomNumber () from the service.*/     Public intGetRandomNumber () {returnMgenerator.nextint (); }}
//Bindingactivity.classPackage Mirror.android.extendingbinder;import Mirror.android.extendingbinder.localservice.localbinder;import Android.app.activity;import Android.content.componentname;import Android.content.context;import Android.content.intent;import Android.content.serviceconnection;import Android.os.bundle;import Android.os.ibinder;import Android.view.menu;import Android.view.menuitem;import Android.view.View;import Android.view.view.onclicklistener;import Android.widget.button;import android.widget.Toast; Public classBindingactivity extends Activity {Privatebutton button;    LocalService Mservice; Boolean Mbound=false; @Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (r.layout.activity_binding); Button=(Button) Findviewbyid (R.id.btn_create_service); Buttonlistener Buttonlistener=NewButtonlistener ();    Button.setonclicklistener (Buttonlistener); } @Overrideprotected voidOnStart () {Super.onstart (); //1.bind to LocalServiceIntent Intent =NewIntent ( This, LocalService.class);    Bindservice (Intent, mconnection, context.bind_auto_create); } @Overrideprotected voidOnPause () {super.onpause (); } @Overrideprotected voidOnStop () {super.onstop (); //2.unbind from service        if(mbound) {unbindservice (mconnection); Mbound=false; }    }        classButtonlistener implements onclicklistener{//3.Call a method from the LocalService. //Create a separate thread if needed;@Override Public voidOnClick (View v) {if(mbound) {intnum =Mservice.getrandomnumber (); Toast.maketext (Getapplicationcontext (),"Number :"+num, Toast.length_short). Show (); }        }    }        PrivateServiceconnection mconnection =Newserviceconnection () {//3.In the client, receive the Binder from the onserviceconnected () callback method//And make calls to the bound service using the methods provided.@Override Public voidonservicedisconnected (componentname name) {Mbound=false; } @Override Public voidonserviceconnected (componentname name, IBinder service) {Localbinder Binder=(localbinder) service; Mservice=Binder.getservice (); Mbound=true; }    };}
//manifest.xml<Application Android:allowbackup="true"Android:icon="@drawable/ic_launcher"Android:label="@string/app_name"Android:theme="@style/apptheme"> <Activity Android:name=". Bindingactivity"Android:label="@string/app_name"> <intent-filter> <action android:name="Android.intent.action.MAIN"/> <category android:name="Android.intent.category.LAUNCHER"/> </intent-filter> </activity> <service android:name=". LocalService"></service> </application>

  

5. Using a Messenger

If you need your service to communicate with remote processesand then you can use a Messenger to provide t He interface for your service.

This technique allows-perform interprocess communication (IPC) without the need to use Aidl.

2.APP Components-services/bound Services

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.