Adding a custom service to the ServiceManager

Source: Internet
Author: User

The Context.getsystemservice method is generally used when we want to use Android's system services. For example we want to get audiomanager, we can:

Audiomanager am = (audiomanager) getsystemservice (Context.audio_service);

The service obtained is actually a binder service that is registered in ServiceManager and then packaged and provided to the user.

You can see the implementation in Contextimpl.java:

   static {         ......        //  When Audiomanager is added to System_service_map, Getsystemservice is called,         //   will get Audiomanager        registerservice from System_service_map (AUDIO _service, new servicefetcher ()  {                 public object createservice (CONTEXTIMPL CTX)  {                      return new audiomanager (CTX);                 }});        ......     } 

Audiomanager is the encapsulation of iaudioservice, the actual operation is done using Iaudioservice, see the code in Audiomanager:

private static Iaudioservice GetService () {if (Sservice! = null) {return sservice;        }//Get binder IBinder B = Servicemanager.getservice (Context.audio_service) from ServiceManager;        Convert Binder to Iaudioservice for easy invocation of Sservice = IAudioService.Stub.asInterface (b);    return sservice; }

Above is how the Android system is used. If we add our own services, how do we do it?

We built 3 test projects in Eclipse:

1)Myservicelib: This is a Lib project, you need to tick the is Library in Eclipse. The next two projects will need to add myservicelib to the library.

    2)  myservice: Used to register the custom service into ServiceManager when Android is powered on. Because ServiceManager is hidden by @hide, so you need to use it to manually add SDK package, add a way to refer to http://my.oschina.net/u/262208/blog/379548. In addition, adding the service requires the system user, so the manifest file needs to be added android:shareduserid= "Android.uid.system" and use platform signature to sign the APK.

3) Myservicetest: Used to test the above two projects.



Let's code it down here.


    1. First Create a aidl file in the Myservicelib project, and the Android build tool will help us generate the appropriate Java class, aidl file as follows

Package Com.test.lib;interface Imyservice {void setValue (int val); int getValue ();}

Two interfaces are defined for testing, SetValue and GetValue.

The Android compilation tool will help us generate a Imyservice Java class in the Gen directory.

2. Create MyService class in MyService project, this class inherits from Imyservice.stub, implements SetValue and GetValue interface, this is a service.

Package com.test.myservice; Import Android.os.remoteexception;import Com.test.lib.IMyService;         public class MyService extends imyservice.stub {private int value;    @Override public void SetValue (int val) throws RemoteException {this.value = val;    } @Override public int getValue () throws RemoteException {return value; } }

Below we will add it to the ServiceManager.

3. Create the Myserviceapplication class in the MyService project

Package com.test.myservice; Import Android.app.application;import Android.os.ServiceManager;        public class Myserviceapplication extends application{@Override public void OnCreate () {super.oncreate ();    Servicemanager.addservice ("MyService", New MyService ()); }     }

This is a application, we want the Android system to start, create this application, in the OnCreate method, create the MyService class, and add it to the ServiceManager. Therefore, I need to modify the next manifest file

  <application         android:name= ". Myserviceapplication "   //Specifies the myserviceapplication      that application created for us    android:allowbackup= "true"         android:icon= "@ Drawable/ic_launcher "        android:persistent=" true "              //  plus persistent=ture, When Activitymanager is created, the app's process is created and the OnCreate method of the myserviceapplication is called          android:label= "@string/app_name"         android:theme= "@style/ Apptheme "&NBSP;> 

Note that this application requires a system user and is signed to run.

In this way, the service side is good, and when the boot, our service is already in the ServiceManager.

4. Below we provide a manager class for easy client use. Create the Mymanager class in Myservicelib:

package com.test.lib; import android.os.remoteexception;import android.os.servicemanager;  public class mymanager {     private static mymanager  instance;    private IMyService myservice;      Public static mymanager getinstance ()  {        if   (Instance == null)  {             instance = new mymanager ();        }         return instance;    }      private mymanager ()  {        //  Get services from ServiceManager         myservice =  IMyService.Stub.asInterface (Servicemanager.getservice ("MyserVICE "));     }     public void setvalue (Int value)  throws remoteexception {        myservice.setvalue ( value);     }     public int getvalue ()  throws  remoteexception {        return myservice.getvalue ();     } }


5. Testing in the myservicetest project

The manager of the service can be easily obtained through mymanager.getinstance () to invoke the remote service. We create an activity to use Mymanager

Package com.test.client; import java.util.random; import android.app.activity;import  android.content.context;import android.media.audiomanager;import android.os.bundle;import  android.os.RemoteException;import android.view.View;import android.view.View.OnClickListener; import android.widget.button;import android.widget.textview;import android.widget.toast;  import com.test.binder.client.r;import com.test.lib.mymanager; public class  mainactivity extends activity implements onclicklistener {      MyManager myManager;         Button btnSetValue;     Button btnGetValue;    TextView tvValue;           @Override     protected void oncreate ( Bundle savedinstancestate)   {        super.oncreate (savedinstancestate);         AudioManager am =  (Audiomanager)  getsystemservice (context.audio_ SERVICE);         setcontentview (R.layout.activity_main);         btnSetValue =  (Button)  findviewbyid (R.id.btn_set_value);         btnGetValue =  (Button)  findviewbyid (r.id.btn_ Get_value);        tvvalue =  (TextView)  findViewById ( R.id.tv_value);                  //  Get mymanager        mymanager =  Mymanager.getinstance ();    }      @Override      public void onclick (View view)  {        switch  (View.getid ())  {         case R.id.btn_set_value:             int value = new random (). NextInt ();             try {                 mymanager.setvalue (value);                 toast.maketext (this,  "Set value  to  "+value+ "  success! ",  0). Show ();             } catch  (remoteexception e)  {                 e.printstacktrace ();          &nbsP;      toast.maketext (this,  "set value fail!",  0). Show ();             }             break;        case r.id.btn_ get_value:            try {                 tvvalue.settext ("Value:" + Mymanager.getvalue ());             } catch   (remoteexception e)  {                 // TODO Auto-generated catch block                 e.printstacktrace ();             }            break;         default:             break;        }    }      }







Adding a custom service to the ServiceManager

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.