Android Activity and service communication (between different processes) detailed _android

Source: Internet
Author: User

In Android, the activity is mainly responsible for the presentation of the front page, the service is mainly responsible for the long-term tasks, so in our actual development, we will often encounter the communication between the work and service, We typically start a background service in an activity, start it through intent, intent we can pass data to the service, and when our service wants to update the UI thread after doing something, what should we do? Next I'll introduce three ways to achieve communication between service and activity

There are three ways in which activity communicates with service:

Inherit Binder class

This method can be used only when your acitivity and service are in the same application and process, for example, you have a service behind the background music in the background, then you can communicate in this way.

Use an example to illustrate how it is used:

1. To see how the service is worded:

 public class LocalService extends Service { 
  //Instantiate Custom Binder class 
  private final IBinder Mbinder = new Localbinder (); 
   //random number generator 
  private final Random mgenerator = new Random (); 
 
  /** 
   * Custom Binder class, this is an inner class, so you can know the object of its outer class, through which the activity knows the object of its service/ 
   public 
  class Localbinder Extends Binder { 
    LocalService getservice () { 
      //Returns the service object associated with the activity, so that in the activity, You can invoke some common methods and public properties in the service return 
      localservice.this 
    } 
 
  @Override public 
  IBinder onbind (Intent Intent) {return 
    mbinder; 
  } 
 
  /** public method, the activity can be invoked * * Public 
  int GetRandomNumber () {return 
   mgenerator.nextint () 
  } 
} 
 

Define an inner class in the service, a subclass of binder, through which the object of the service is passed to the activity so that the activity can invoke the common methods and public properties in the service, but this way, Be sure to be in the same process and in the same application.

2. Look again at the corresponding activity code:

public class Bindingactivity extends activity {LocalService mservice; 
 
  Boolean mbound = false; 
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
  Setcontentview (R.layout.main); 
    } @Override protected void OnStart () {Super.onstart (); 
    Bind the service, binding will call the Mconnetion onserviceconnected method Intent Intent = new Intent (this, localservice.class); 
  Bindservice (Intent, mconnection, context.bind_auto_create); 
    } @Override protected void OnStop () {super.onstop (); 
      Untied service, which saves memory if (mbound) {unbindservice (mconnection); 
    Mbound = false; }/** user clicks button to read random number in service * * public void OnButtonClick (View v) {if (Mbound) {//Service 
      object, to read the random number int num = Mservice.getrandomnumber (); 
    Toast.maketext (This, "number:" + num, Toast.length_short). Show (); }/** serviceconnection, used to bind service's */privatE serviceconnection mconnection = new Serviceconnection () {@Override public void onserviceconnected (Component Name ClassName, IBinder service) {//already bound LocalService, strongly IBinder object, calling method to get LocalService object Localbinde 
      R binder = (localbinder) service; 
      Mservice = Binder.getservice (); 
    Mbound = true; 
    @Override public void onservicedisconnected (ComponentName arg0) {mbound = false; 
} 
  }; 
 }

This is where the LocalService object is obtained by IBinder, and then the public method is invoked.

Using Messenger

The above method can only be used in the same process, and if you want to communicate with the service of another process, use Messenger.

In fact, the way to implement IPC, there are aidl, but the recommended use of Messenger, there are two points of benefit:

1. Using Messenger is a much simpler way to implement than using Aidl

2. When using Messenger, all messages from the activity are queued and will not request service at the same time, so it is thread-safe. If

Your program is to have multiple threads to access the service, you can use Aidl, or the best way to use Messenger.

However, in fact, the messenger is the bottom of the implementation of AIDL, look at the implementation of the way, first look at the service code:

 public class Messengerservice extends Service {/** used in handler message type/static final int msg_say_hello = 1; /** * Handler/class Incominghandler extends Handler {@Override public voi in service handling activity. D handlemessage (message msg) {switch (msg.what) {case MSG_SAY_HELLO:Toast.makeText (getapplic 
          Ationcontext (), "hello!", Toast.length_short). Show (); 
        Break 
      Default:super.handleMessage (msg); 
   }/** * This messenger can be associated with the service handler,activity send message to Service,service through handler. 
 
  * Final Messenger Mmessenger = new Messenger (new Incominghandler ()); /** * When the activity binds the service, this method returns a ibinder,activity with the messenger created by the IBinder, which communicates with the handler of the service. * * @Over Ride public IBinder Onbind (Intent Intent) {Toast.maketext (Getapplicationcontext (), "binding", Toast.length_short) 
    . Show (); 
  return Mmessenger.getbinder (); 
 
 } 
}

  Look again at the activity's code:

public class Activitymessenger extends activity {/** Messenger object sending message to service * Messenger mservice = null; 
 
  /** judge If there is no binding service * * Boolean mbound; Private Serviceconnection mconnection = new Serviceconnection () {public void onserviceconnected (ComponentName ClassN AME, IBinder Service) {//activity has been bound service//The Messenger object is created by the parameter service, which sends a message to the service and the Servic 
      E for communication mservice = new Messenger (service); 
    Mbound = true; 
      public void onservicedisconnected (ComponentName className) {mservice = null; 
    Mbound = false; 
 
  } 
  }; 
    public void SayHello (View v) {if (!mbound) return; 
    Send a message to service msg = Message.obtain (null, Messengerservice.msg_say_hello, 0, 0); 
    try {mservice.send (msg); 
    catch (RemoteException e) {e.printstacktrace (); }} @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (SavediNstancestate); 
  Setcontentview (R.layout.main); 
    } @Override protected void OnStart () {Super.onstart (); 
  Bind service Bindservice (this, messengerservice.class), mconnection, context.bind_auto_create); 
    } @Override protected void OnStop () {super.onstop (); 
      Unbound if (mbound) {unbindservice (mconnection); 
    Mbound = false; 
 } 
  } 
}

Note: The above code can only be implemented from the activity to the service to send messages, if you want to send messages from the service to the activity, as long as the code in turn to write.

Using Aidl

Aidl,android Interface Definition Language. The establishment of AIDL services is more complex than the establishment of ordinary services, the specific steps are as follows:

(1) Create a file with an extension of aidl in the Java package directory of the Eclipse Android project. The syntax for this file is similar to Java code, but slightly different. See the contents of the example in detail.

(2) If the contents of the Aidl file are correct, ADT will automatically generate a Java interface file (*.java).

(3) Establish a service class (a subclass of services).

(4) Implement the Java interface generated by the Aidl file.

(5) Configure the Aidl service in the Androidmanifest.xml file, especially to note that the Android:name attribute value in the,<action> tag is the ID of the client to reference the service, which is the parameter value of the intent class.

Thank you for reading, I hope to help you, thank you for your support for this site!

Related Article

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.