. NET programmer play to Android development---() Android binding service

Source: Internet
Author: User

A binding service is a service that is used locally in Android, where clients and services work in the same process and do not require cross-process operations. The client creates an association with the service through the Bindservice method

The following example shows how the client invokes the service's Get Time method

1. Create a binding service

First create the service,

The service creates an inner class Timebinder, inherits the binder, returns the service instance through the Onbind callback,

Creates a public method of getting time in the service for the client to invoke

Package Com.example.helloword;import Java.text.simpledateformat;import Java.util.date;import android.app.Service; Import Android.content.componentname;import Android.content.intent;import android.content.ServiceConnection; Import Android.os.binder;import Android.os.ibinder;public class Bindservice extends Service {private final IBinder Binder= new Timebinder ();//Create an internal binding class public class Timebinder extends Binder {bindservice getService () {//Re         Turn this instance of LocalService so clients can call public methods return bindservice.this; }} @Overridepublic IBinder Onbind (Intent arg0) {//TODO auto-generated method Stubreturn Binder;}/* Only executed once at creation time */@          Override public void OnCreate () {super.oncreate ();            */* @Override public void OnDestroy () {Super.ondestroy () when disconnecting or stopservice;     *//@Override public void Onrebind (Intent Intent) {super.onrebind (Intent) when new attempt binding is performed;     } @Override public void OnStart (Intent Intent, int startid) {Super.onstart (Intent, Startid);     } @Override public boolean onunbind (Intent Intent) {return super.onunbind (Intent); }/*, each time the StartService executes the method, the OnStart () method is automatically executed when the method executes */@Override public int Onstartcommand (Intent Intent, int     Flags, int startid) {return Super.onstartcommand (intent, flags, Startid); }//Get Time public String Getcurtime () {//date format SimpleDateFormat format = new SimpleDateFormat ("Yyyy-mm-dd h:m:s");D ate dat E = new Date (); return Format.format (Date.gettime ());}}

2. Invoking the binding service

On the client side, bind the service through Bindservice

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "vertical" >    <button        android:id= "@+id/btngettime" android:layout_width= "Wrap_        Content "        android:layout_height=" wrap_content "        android:text=" Get Time "/>    <textview        android:id = "@+id/tvtime"        android:layout_width= "262DP"        android:layout_height= "wrap_content"        android:text= " TextView "/></linearlayout>
The client rewrites the Serviceconnection two methods.The onserviceconnected system calls this to pass the IBinder returned in the service Onbind onservicedisconnected () was accidentally lost in connection with the system, call this
Package Com.example.helloword;import Com.example.helloword.bindservice.timebinder;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.View; Import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.textview;public class Bindserviceactivity extends Activity {private Button btntime;//get time private TextView tvtime;//Show time Bindservice Bindserv Ice; @Overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate ( Savedinstancestate); Setcontentview (r.layout.bindservicelayout); Btntime= (Button) Findviewbyid (R.id.btngettime); Tvtime= (TextView) Findviewbyid (r.id.tvtime); Btntime.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated method Stubtvtime.settext (Bindservice.getcurtime ());}});} @OvErride protected void OnStart () {Super.onstart ();        Bind to LocalService Intent Intent = new Intent (this, bindservice.class);    Bindservice (Intent, mconnection, context.bind_auto_create); }private serviceconnection mconnection = new Serviceconnection () {@Override public void onserviceconnected (  ComponentName ClassName, IBinder service) {//We ' ve bound to LocalService, cast the IBinder and        Get LocalService instance Timebinder binder = (timebinder) service;                  Bindservice=binder.getservice ();        } @Override public void onservicedisconnected (ComponentName arg0) {bindservice=null;    }    }; }


Androidmanifest.xml

  <activity android:name= "com.example.helloword.BindServiceActivity" >             <intent-filter>                < Action android:name= "Android.intent.action.MAIN"/>                <category android:name= " Android.intent.category.LAUNCHER "/>            </intent-filter>        </activity>                                <service   Android:name= ". Bindservice ">     <intent-filter>          <action android:name=" Com.example.helloword.BindService "/>          <category android:name= "Android.intent.category.default"/>    </intent-filter>  





. NET programmer play to Android development---() Android binding service

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.