Android IPC Mechanism ACtivity Binding Service Communication Code Example

  • 2021-12-09 09:56:47
  • OfStack

The Binder communication process is similar to the TCP/IP service connection process binder4 large architecture Server (server), Client (client), ServiceManager (DNS), and Binder driver (router)

Among them, Server, Client and ServiceManager run in user space, and drivers run in kernel space. The relationship between these four roles is similar to that of the Internet: Server is the server, Client is the client terminal, SMgr is the domain name server (DNS), and the driver is the router.

book.java


package com.example.android_binder_testservice;

import android.os.Parcel;
import android.os.Parcelable;

public class Book implements Parcelable {
  private String bookName;
  private String author;
  private int publishDate;

  public Book() {

  }

  public Book(String bookName, String author, int publishDate) {
    super();
    this.bookName = bookName;
    this.author = author;
    this.publishDate = publishDate;
  }

  public String getBookName() {
    return bookName;
  }

  public void setBookName(String bookName) {
    this.bookName = bookName;
  }

  public String getAuthor() {
    return author;
  }

  public void setAuthor(String author) {
    this.author = author;
  }

  public int getPublishDate() {
    return publishDate;
  }

  public void setPublishDate(int publishDate) {
    this.publishDate = publishDate;
  }

  @Override
  public int describeContents() {
    return 0;
  }

  @Override
  public void writeToParcel(Parcel out, int flags) {
    out.writeString(bookName);
    out.writeString(author);
    out.writeInt(publishDate);
    
  }
  
  
  

  public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() {
    @Override
    public Book[] newArray(int size) {
      return new Book[size];
    }


    @Override
    public Book createFromParcel(android.os.Parcel source) {
      return new Book(source);
    }
  };

  public Book(Parcel in) {
    bookName = in.readString();
    author = in.readString();
    publishDate = in.readInt();
  }
}

Above is a realization of parcelable entity class, is the serialization of book, putExtra to Service will be written into memory to speed up the program

mainActivity.java


package com.example.android_binder_testservice;

import android.os.Bundle;
import android.util.Log;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
  Button startServiceButton;//  Start service button 
  Button shutDownServiceButton;//  Close service button 
  Button startBindServiceButton;//  Start binding service button 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getWidget();
    regiestListener();
  }
  public void getWidget(){
    startServiceButton = (Button) findViewById(R.id.startService);
    startBindServiceButton = (Button) findViewById(R.id.bindService);
    shutDownServiceButton = (Button) findViewById(R.id.stopService);
  }
  public void regiestListener() {
    startServiceButton.setOnClickListener(startService);
    shutDownServiceButton.setOnClickListener(shutdownService);
    startBindServiceButton.setOnClickListener(startBinderService);
  }
  /**  Start event listening for the service  */
  public Button.OnClickListener startService = new Button.OnClickListener() {
    public void onClick(View view) {
      /**  Start the service when the button is clicked  */
      Intent intent = new Intent(MainActivity.this,
          CountService.class);
      startService(intent);
      
      Log.v("MainStadyServics", "start Service");
    }
  };
  /**  Shut down the service  */
  public Button.OnClickListener shutdownService = new Button.OnClickListener() {
    public void onClick(View view) {
      /**  Start the service when the button is clicked  */
      Intent intent = new Intent(MainActivity.this,
          CountService.class);
      /**  Quit Activity Yes, stop service  */
      stopService(intent);
      Log.v("MainStadyServics", "shutDown serveice");
    }
  };
  /**  Object for the binding service Activity */
  public Button.OnClickListener startBinderService = new Button.OnClickListener() {
    public void onClick(View view) {
      /**  Start the service when the button is clicked  */
      Intent intent = new Intent(MainActivity.this, UseBrider.class);
      startActivity(intent);
      Log.v("MainStadyServics", "start Binder Service");
    }
  };

}

onStartCommand () of Service is called when Service is started with startService () in mainActivity

When using bindService (), the onBind () method will be called, and you may wonder why you didn't see the bindService () method

The point is

Intent intent = new Intent(MainActivity.this, UseBrider.class);
startActivity(intent);

Continue on the code

UseBrider.java


/**  Pass bindService And unBindSerivce Start and end the service in the way of  */
public class UseBrider extends FragmentActivity {
  /**  Parameter setting  */
  CountService countService;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(new UseBriderFace(this));

    Intent intent = new Intent(UseBrider.this, CountService.class);
    intent.putExtra("book", new Book("name", "an", 1999));

      /**  Enter Activity Start service 

         * conn
         */
    bindService(intent, conn, Context.BIND_AUTO_CREATE);

  }

  private ServiceConnection conn = new ServiceConnection() {
    /*
     *  This method gets the CountService Adj. onBind Object returned in the Binder Object 
     *  Then you can do some kind of operation on the service 
     */
    public void onServiceConnected(ComponentName name, IBinder service) {
      // TODO Auto-generated method stub
      countService = ((CountService.ServiceBinder) service).getService();
      countService.callBack();
    }

    /**  Operation when the service object cannot be obtained  */
    public void onServiceDisconnected(ComponentName name) {
      // TODO Auto-generated method stub
      countService = null;
    }

  };

  protected void onDestroy() {
    super.onDestroy();
    this.unbindService(conn);
    Log.v("MainStadyServics", "out");
  }
}

UseBriderFace.java


public class UseBriderFace extends View{
      /** Create Parameters */
    public UseBriderFace(Context context){
      super(context);
    }
    public void onDraw(Canvas canvas){
      canvas.drawColor(Color.WHITE);// Draw a white background 
        /** Draw text */
      Paint textPaint = new Paint();
      textPaint.setColor(Color.RED);
      textPaint.setTextSize(30);
      canvas.drawText(" Using binding services ", 10, 30, textPaint);
      textPaint.setColor(Color.GREEN);
      textPaint.setTextSize(18);
      canvas.drawText(" After using the binding service, this Activity After closing ", 20, 60, textPaint);
      canvas.drawText(" The bound service will also shut down ", 5, 80, textPaint);

    }
  }

The UseBriderFace. java class is actually a layout defined by java, which can be replaced by an xml file

countService.java


package com.example.android_binder_testservice;

/** Incoming package */
import android.app.Service;//  Classes of services 
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.os.Binder;
import android.content.Intent;
import android.util.Log;

/**  Counted services  */
public class CountService extends Service {
  private String TAG = CountService.class.getSimpleName();
  /**  Create Parameters  */
  boolean threadDisable;
  int count;
  Book book;
/*
 *  When passing bindService() Start CountService This method is called when the 1 A ServiceBinder Object 
 *  This Binder Object encapsulates the 1 A CountService Example, 
 *  The client can pass the ServiceBinder On the server side 1 Some operations 
 */
  public IBinder onBind(Intent intent) {
    Log.i(TAG, "onBind");
    book = intent.getParcelableExtra("book");
    return new ServiceBinder();
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(TAG, "onStartCommand");
    return super.onStartCommand(intent, flags, startId);
  }

  @Override
  public boolean onUnbind(Intent intent) {
    Log.i(TAG, "onUnbind");
    return super.onUnbind(intent);
  }

  @Override
  public void onRebind(Intent intent) {
    Log.i(TAG, "onRebind");
    super.onRebind(intent);
  }

  public void onCreate() {
    super.onCreate();
    /**  Create 1 Threads, per second counter plus 1 And in the console Log Output  */
    new Thread(new Runnable() {
      public void run() {
        while (!threadDisable) {
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {

          }
          count++;
          Log.v("CountService", "Count is" + count);
        }
      }
    }).start();
    Log.i(TAG, "onCreate");
  }

  public void onDestroy() {
    super.onDestroy();
    /**  Terminate the counting process when the service stops  */
    this.threadDisable = true;
    Log.i(TAG, "onDestroy");
  }

  public int getConunt() {
    return count;
  }
  public void callBack(){
    Log.i(TAG, "hello,i am a method of CountService");
  }

  class ServiceBinder extends Binder {
    public CountService getService() {

      return CountService.this;
    }
  }
}

With the code explanation, I can't think of it

Download address of source code: http://git.oschina.net/zwh_9527/Binder


Related articles: