Android IPC Binding service implements local communication _android

Source: Internet
Author: User

* * Writing reasons: The implementation and understanding of communication across processes is an important part of Android advanced. The following bloggers share some knowledge about IPC, their operations and their understanding of the process of learning IPC.
This chapter prepares for the use of the following Messenger and Aidl, which focuses on the binding of the Android service and the knowledge of the communication between the activity and the local service. **

Brief introduction

We all know that there are two ways to start a service:StartService () and Bindservice (). compared to the first approach,Bindservice () is able to more flexibly implement data communications with activity at the startup end, the first startup means there is no direct correlation between activity and service, and it is difficult to communicate directly (of course, can also be implemented using the broadcast or the event bus. The use of bindings to start a service enables communication between service.

Here's how the binding service implements the local communication process.

Instance

In conjunction with the picture we will simulate the opening of a background to perform the update function as an example to explain the binding of local service.

First, we need to analyze the scenario of this requirement: first we have to click the Start button to open the background update data, return the data to the activity in the background and show the progress in the ProgressBar; When we click on the pause, the background is paused, and when we click the Stop button, the background is closed. In this case, a service is also used to pass data to the activity through broadcast. Because it is just an instance, there are some bugs in the threading operation, and I hope everyone can help correct me.

The activity is laid out as follows:

Service implementation:

First look at the implementation of the service:

The idea is this: first inherit the Binder class to create the Mybinder class, the Mybinder as a service and activity communication agent, So write a good method inside the Mybinder to invoke the method in the service indirectly for the activity to invoke (as in this case Callpauseupgrade ()). There are two ways to get a IBinder object in addition to rewriting it directly, but not in the first place. In the service we open a thread that simulates the continuous update progress bar in this thread until Isstop is false or progress is greater than or equal to 100, and then broadcasts the progress, allowing the activity to receive the broadcast for progress bar updates. The method for activity invocation in the service implements the function of pausing and stopping thread, with reference to the code of the specific procedure.

public class Upgradeservice extends Service {private thread thread;
 Private Intent Intent;
 private int progress;
 Private Boolean isstop;
  public class Mybinder extends binder{public void Callpauseupgrade () {pauseupgrade ();
  public void Callstopupgrade () {stopupgrade ();
  }} private void Stopupgrade () {progress = 0;
  Isstop = false;
  Intent.putextra ("Progress", progress);
 Sendbroadcast (Intent);
  @Override public void OnCreate () {super.oncreate ();
  progress = 0;
  Isstop = true;
  Intent = new Intent (); thread = new Thread (new Runnable () {@Override public void run () {while (isstop) {try {Thread.Sleep) (
     1000);
     catch (Interruptedexception e) {e.printstacktrace ();
     } progress = Progress +5;
     Intent.putextra ("Progress", progress);
     Intent.setaction ("Upgrade_action");
     Sendbroadcast (Intent);
    if (progress>=100) break;
  }

   }
  });
 Thread.Start ();
  private void Pauseupgrade () {Todo:pause the Upgrade Toast.maketext (Getapplicationcontext (), pause, Toast.length_short). Show ();
 Isstop = false;
 @Override public IBinder onbind (Intent Intent) {return new Mybinder (); }
}

Activity implementation

The following is the communication code to implement the service with the client. The main idea is: Register the broadcast to realize the return of service data; When you click the Start button to bind to the service, create the Serviceconnection object to implement the Serviceconnection interface, Callback the logic of both the success and the failure of the binding respectively. Gets the Mybinder object when successful and sets the Isbound value to True, and sets the Isbound to False when it fails. Click the Callpauseupgrade () method of the pause call Mybinder object to invoke the Pauseupgrade () method in the service indirectly. Click the Stop Call Callstopupgrade () method and unbind it. Note The Unbind event can only be executed once, or the program crashes.

Concrete implementation is not difficult, the main is to carefully understand the flow chart above.

public class Mainactivity extends appcompatactivity implements view.onclicklistener{private Button Mbtstart;
 Private Button mbtstop;
 Private Button Mbtpause;
 Private ProgressBar mpbprogress;
 Private Upgradeservice.mybinder Mybinder;
 Private Boolean isbound;
 Private Upgradereceiver Upgradereceiver;
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_main);
  Intentfilter intentfilter = new Intentfilter ();
  Intentfilter.addaction ("Upgrade_action");
  Upgradereceiver = new Upgradereceiver ();
  Registerreceiver (Upgradereceiver,intentfilter);
  Initview ();

 Initevent (); The public class Upgradereceiver extends broadcastreceiver{@Override the public void onreceive (context context, Intent in
  Tent) {mpbprogress.setprogress (Intent.getintextra ("Progress", 0));
  }} @Override protected void OnDestroy () {Super.ondestroy ();
 Unregisterreceiver (Upgradereceiver); private void Initevent () {Mbtpause.setonclicklistener (this);
  Mbtstart.setonclicklistener (this);
 Mbtstop.setonclicklistener (this);
  private void Initview () {mbtpause = (Button) Findviewbyid (r.id.bt_pause);
  Mbtstart = (Button) Findviewbyid (R.id.bt_start);
  Mbtstop = (Button) Findviewbyid (r.id.bt_stop);
 Mpbprogress = (ProgressBar) Findviewbyid (r.id.pb_progress); @Override public void OnClick (View v) {switch (V.getid ()) {Case R.id.bt_pause:if (isbound&&mybinder!
    =null) {Mybinder.callpauseupgrade ();
   } break;
    Case R.id.bt_start:bindservice (New Intent (Mainactivity.this,upgradeservice.class), conn,bind_auto_create);
   Break
     Case R.id.bt_stop:if (isbound) {mybinder.callstopupgrade ();
     Unbindservice (conn);
    Isbound = false;
  } break; } private Serviceconnection conn = new Serviceconnection () {@Override public void onserviceconnected (Componentna Me name, IBinder service) {if (service!= null) {Mybinder = (UpgradEservice.mybinder) Service;
   Isbound = true;
  @Override public void onservicedisconnected (componentname name) {Isbound = false;
}
 }; }

Summarize:

This article is intended for the following messenger and Aidl across process communications, and in fact the individual feels that real development can use Eventbus or Rxjava instead of communicating with various components of the process, and interested readers can try it on their own.

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.