本文參考http://blog.csdn.net/saintswordsman/article/details/5130947

android的多进程是通过Binder来实现的,一个类,继承了Binder,那么它的对象就能够被远程的进程使用了(前提是远程进程获取了这个类的对象【对象的引用】,至于如怎样获得看下文),怎么使用呢?在Android中, 则採用AIDL(Android InterfaceDefinition Language:接口定义语言)方式实现。所以我们必须写后缀为.aidl的文件。.aidl文件放在src以下,刷新一下就会生成同名的.java文件

文件:forActivity.aidl

[java] view
plain
copy

  1. package com.styleflying.AIDL;
  2. interface forActivity {
  3. void performAction();
  4. }

文件:forService.aidl

[java] view
plain
copy

  1. package com.styleflying.AIDL;
  2. import com.styleflying.AIDL.forActivity;
  3. interface forService {
  4. void registerTestCall(forActivity cb);
  5. void invokCallBack();
  6. }

这两个文件和Java文件放置的地方一样,看包名。

在Eclipse中它们将被自己主动编译为forActivity.java和forService.java。它们存放在gen文件夹下。

为了方便手头无法演练的读者。代码贴上,不用细看。

文件forActivity.java:

[java] view
plain
copy

  1. /*
  2. * This file is auto-generated.  DO NOT MODIFY.
  3. * Original file: D://workspace//AIDLTest//src//com//styleflying//AIDL//forActivity.aidl
  4. */
  5. package com.styleflying.AIDL;
  6. import java.lang.String;
  7. import android.os.RemoteException;
  8. import android.os.IBinder;
  9. import android.os.IInterface;
  10. import android.os.Binder;
  11. import android.os.Parcel;
  12. public interface forActivity extends android.os.IInterface
  13. {
  14. /** Local-side IPC implementation stub class. */
  15. public static abstract class Stub extends android.os.Binder implements com.styleflying.AIDL.forActivity
  16. {
  17. private static final java.lang.String DESCRIPTOR = "com.styleflying.AIDL.forActivity";
  18. /** Construct the stub at attach it to the interface. */
  19. public Stub()
  20. {
  21. this.attachInterface(this, DESCRIPTOR);
  22. }
  23. /**
  24. * Cast an IBinder object into an forActivity interface,
  25. * generating a proxy if needed.
  26. */
  27. public static com.styleflying.AIDL.forActivity asInterface(android.os.IBinder obj)
  28. {
  29. if ((obj==null)) {
  30. return null;
  31. }
  32. android.os.IInterface iin = (android.os.IInterface)obj.queryLocalInterface(DESCRIPTOR);
  33. if (((iin!=null)&&(iin instanceof com.styleflying.AIDL.forActivity))) {
  34. return ((com.styleflying.AIDL.forActivity)iin);
  35. }
  36. return new com.styleflying.AIDL.forActivity.Stub.Proxy(obj);
  37. }
  38. public android.os.IBinder asBinder()
  39. {
  40. return this;
  41. }
  42. @Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException
  43. {
  44. switch (code)
  45. {
  46. case INTERFACE_TRANSACTION:
  47. {
  48. reply.writeString(DESCRIPTOR);
  49. return true;
  50. }
  51. case TRANSACTION_performAction:
  52. {
  53. data.enforceInterface(DESCRIPTOR);
  54. this.performAction();
  55. reply.writeNoException();
  56. return true;
  57. }
  58. }
  59. return super.onTransact(code, data, reply, flags);
  60. }
  61. private static class Proxy implements com.styleflying.AIDL.forActivity
  62. {
  63. private android.os.IBinder mRemote;
  64. Proxy(android.os.IBinder remote)
  65. {
  66. mRemote = remote;
  67. }
  68. public android.os.IBinder asBinder()
  69. {
  70. return mRemote;
  71. }
  72. public java.lang.String getInterfaceDescriptor()
  73. {
  74. return DESCRIPTOR;
  75. }
  76. public void performAction() throws android.os.RemoteException
  77. {
  78. android.os.Parcel _data = android.os.Parcel.obtain();
  79. android.os.Parcel _reply = android.os.Parcel.obtain();
  80. try {
  81. _data.writeInterfaceToken(DESCRIPTOR);
  82. mRemote.transact(Stub.TRANSACTION_performAction, _data, _reply, 0);
  83. _reply.readException();
  84. }
  85. finally {
  86. _reply.recycle();
  87. _data.recycle();
  88. }
  89. }
  90. }
  91. static final int TRANSACTION_performAction = (IBinder.FIRST_CALL_TRANSACTION + 0);
  92. }
  93. public void performAction() throws android.os.RemoteException;
  94. }

文件forService.java:

[java] view
plain
copy

  1. /*
  2. * This file is auto-generated.  DO NOT MODIFY.
  3. * Original file: D://workspace//AIDLTest//src//com//styleflying//AIDL//forService.aidl
  4. */
  5. package com.styleflying.AIDL;
  6. import java.lang.String;
  7. import android.os.RemoteException;
  8. import android.os.IBinder;
  9. import android.os.IInterface;
  10. import android.os.Binder;
  11. import android.os.Parcel;
  12. public interface forService extends android.os.IInterface
  13. {
  14. /** Local-side IPC implementation stub class. */
  15. public static abstract class Stub extends android.os.Binder implements com.styleflying.AIDL.forService
  16. {
  17. private static final java.lang.String DESCRIPTOR = "com.styleflying.AIDL.forService";
  18. /** Construct the stub at attach it to the interface. */
  19. public Stub()
  20. {
  21. this.attachInterface(this, DESCRIPTOR);
  22. }
  23. /**
  24. * Cast an IBinder object into an forService interface,
  25. * generating a proxy if needed.
  26. */
  27. public static com.styleflying.AIDL.forService asInterface(android.os.IBinder obj)
  28. {
  29. if ((obj==null)) {
  30. return null;
  31. }
  32. android.os.IInterface iin = (android.os.IInterface)obj.queryLocalInterface(DESCRIPTOR);
  33. if (((iin!=null)&&(iin instanceof com.styleflying.AIDL.forService))) {
  34. return ((com.styleflying.AIDL.forService)iin);
  35. }
  36. return new com.styleflying.AIDL.forService.Stub.Proxy(obj);
  37. }
  38. public android.os.IBinder asBinder()
  39. {
  40. return this;
  41. }
  42. @Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException
  43. {
  44. switch (code)
  45. {
  46. case INTERFACE_TRANSACTION:
  47. {
  48. reply.writeString(DESCRIPTOR);
  49. return true;
  50. }
  51. case TRANSACTION_registerTestCall:
  52. {
  53. data.enforceInterface(DESCRIPTOR);
  54. com.styleflying.AIDL.forActivity _arg0;
  55. _arg0 = com.styleflying.AIDL.forActivity.Stub.asInterface(data.readStrongBinder());
  56. this.registerTestCall(_arg0);
  57. reply.writeNoException();
  58. return true;
  59. }
  60. case TRANSACTION_invokCallBack:
  61. {
  62. data.enforceInterface(DESCRIPTOR);
  63. this.invokCallBack();
  64. reply.writeNoException();
  65. return true;
  66. }
  67. }
  68. return super.onTransact(code, data, reply, flags);
  69. }
  70. private static class Proxy implements com.styleflying.AIDL.forService
  71. {
  72. private android.os.IBinder mRemote;
  73. Proxy(android.os.IBinder remote)
  74. {
  75. mRemote = remote;
  76. }
  77. public android.os.IBinder asBinder()
  78. {
  79. return mRemote;
  80. }
  81. public java.lang.String getInterfaceDescriptor()
  82. {
  83. return DESCRIPTOR;
  84. }
  85. public void registerTestCall(com.styleflying.AIDL.forActivity cb) throws android.os.RemoteException
  86. {
  87. android.os.Parcel _data = android.os.Parcel.obtain();
  88. android.os.Parcel _reply = android.os.Parcel.obtain();
  89. try {
  90. _data.writeInterfaceToken(DESCRIPTOR);
  91. _data.writeStrongBinder((((cb!=null))?(cb.asBinder()):(null)));
  92. mRemote.transact(Stub.TRANSACTION_registerTestCall, _data, _reply, 0);
  93. _reply.readException();
  94. }
  95. finally {
  96. _reply.recycle();
  97. _data.recycle();
  98. }
  99. }
  100. public void invokCallBack() throws android.os.RemoteException
  101. {
  102. android.os.Parcel _data = android.os.Parcel.obtain();
  103. android.os.Parcel _reply = android.os.Parcel.obtain();
  104. try {
  105. _data.writeInterfaceToken(DESCRIPTOR);
  106. mRemote.transact(Stub.TRANSACTION_invokCallBack, _data, _reply, 0);
  107. _reply.readException();
  108. }
  109. finally {
  110. _reply.recycle();
  111. _data.recycle();
  112. }
  113. }
  114. }
  115. static final int TRANSACTION_registerTestCall = (IBinder.FIRST_CALL_TRANSACTION + 0);
  116. static final int TRANSACTION_invokCallBack = (IBinder.FIRST_CALL_TRANSACTION + 1);
  117. }
  118. public void registerTestCall(com.styleflying.AIDL.forActivity cb) throws android.os.RemoteException;
  119. public void invokCallBack() throws android.os.RemoteException;
  120. }

我们能够看到在.java文件里都定义了一个抽象类Stub,Stub就是继承Binder。

好了,那我们那里用到了Binder呢?没错,就是Service,Service使用有两种方法,startService。bindeService。bindeService时在实现Service就必须实现 onBind 返回一个Binder对象,这个Binder对象就会被activity回调使用。

这样activity跟service就能够通信了。

当然是activity能够调用service了。

接下来的样例还实现了相互调用。

看mAIDLService.java:

[java] view
plain
copy

  1. package com.styleflying.AIDL;
  2. import android.app.Service;
  3. import android.content.Intent;
  4. import android.os.IBinder;
  5. import android.os.RemoteCallbackList;
  6. import android.os.RemoteException;
  7. import android.util.Log;
  8. public class mAIDLService extends Service {
  9. private static final String TAG = "AIDLService";
  10. private forActivity callback;
  11. private void Log(String str) {
  12. Log.d(TAG, "------ " + str + "------");
  13. }
  14. @Override
  15. public void onCreate() {
  16. Log("service create");
  17. }
  18. @Override
  19. public void onStart(Intent intent, int startId) {
  20. Log("service start id=" + startId);
  21. }
  22. @Override
  23. public IBinder onBind(Intent t) {
  24. Log("service on bind");
  25. return mBinder;
  26. }
  27. @Override
  28. public void onDestroy() {
  29. Log("service on destroy");
  30. super.onDestroy();
  31. }
  32. @Override
  33. public boolean onUnbind(Intent intent) {
  34. Log("service on unbind");
  35. return super.onUnbind(intent);
  36. }
  37. public void onRebind(Intent intent) {
  38. Log("service on rebind");
  39. super.onRebind(intent);
  40. }
  41. private final forService.Stub mBinder = new forService.Stub() {
  42. @Override
  43. public void invokCallBack() throws RemoteException
  44. {
  45. callback.performAction();
  46. }
  47. @Override
  48. public void registerTestCall(forActivity cb) throws RemoteException
  49. {
  50. callback = cb;
  51. }
  52. };
  53. }

当中mBinder就是给activity调用了。然而这个类中的mBinder 中的registerTestCall传递的forActivity就是能service调用activity用的。

看mAIDLActivity.java:

[java] view
plain
copy

  1. package com.styleflying.AIDL;
  2. import android.app.Activity;
  3. import android.content.ComponentName;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.ServiceConnection;
  7. import android.os.Bundle;
  8. import android.os.IBinder;
  9. import android.os.RemoteException;
  10. import android.util.Log;
  11. import android.view.View;
  12. import android.view.View.OnClickListener;
  13. import android.widget.Button;
  14. import android.widget.Toast;
  15. public class mAIDLActivity extends Activity {
  16. private static final String TAG = "AIDLActivity";
  17. private Button btnOk;
  18. private Button btnCancel;
  19. private Button btnCallBack;
  20. private void Log(String str) {
  21. Log.d(TAG, "------ " + str + "------");
  22. }
  23. private forActivity mCallback = new forActivity.Stub() {
  24. public void performAction() throws RemoteException
  25. {
  26. Toast.makeText(mAIDLActivity.this, "this toast is called from service", 1).show();
  27. }
  28. };
  29. forService mService;
  30. private ServiceConnection mConnection = new ServiceConnection() {
  31. public void onServiceConnected(ComponentName className,
  32. IBinder service) {
  33. mService = forService.Stub.asInterface(service);
  34. try {
  35. mService.registerTestCall(mCallback);}
  36. catch (RemoteException e) {
  37. }
  38. }
  39. public void onServiceDisconnected(ComponentName className) {
  40. Log("disconnect service");
  41. mService = null;
  42. }
  43. };
  44. @Override
  45. public void onCreate(Bundle icicle) {
  46. super.onCreate(icicle);
  47. setContentView(R.layout.main);
  48. btnOk = (Button)findViewById(R.id.btn_ok);
  49. btnCancel = (Button)findViewById(R.id.btn_cancel);
  50. btnCallBack = (Button)findViewById(R.id.btn_callback);
  51. btnOk.setOnClickListener(new OnClickListener() {
  52. public void onClick(View v) {
  53. Bundle args = new Bundle();
  54. Intent intent = new Intent(mAIDLActivity.this, mAIDLService.class);
  55. intent.putExtras(args);
  56. bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
  57. startService(intent);
  58. }
  59. });
  60. btnCancel.setOnClickListener(new OnClickListener() {
  61. public void onClick(View v) {
  62. unbindService(mConnection);
  63. //stopService(intent);
  64. }
  65. });
  66. btnCallBack.setOnClickListener(new OnClickListener() {
  67. @Override
  68. public void onClick(View v)
  69. {
  70. try
  71. {
  72. mService.invokCallBack();
  73. } catch (RemoteException e)
  74. {
  75. // TODO Auto-generated catch block
  76. e.printStackTrace();
  77. }
  78. }
  79. });
  80. }
  81. }

当中button点击bindeService时就会触发ServiceConnection,返回了mService = forService.Stub.asInterface(service); activity跟service实现了通信,再mService.registerTestCall(mCallback);} 这样service跟activity又能通信了。在mService.invokCallBack();顺序是activity->service->activity

还有几篇android多进程通信写得不错一并贴出来

http://www.cnblogs.com/BeyondAnyTime/p/3204119.html

http://www.apkbus.com/android-83462-1-1.html

http://blog.csdn.net/baodinglaolang/article/details/9903499

android 多进程 Binder AIDL Service的更多相关文章

  1. Android使用binder访问service的方式(一)

    binder机制是贯穿整个android系统的进程间访问机制,经常被用来访问service,我们结合代码看一下binder在访问service的情形下是怎么具体使用的. service 你可以理解成没 ...

  2. Android 使用binder访问service的方式

    binder机制是贯穿整个Android系统的进程间访问机制,经常被用来访问service,我们结合代码看一下binder在访问service的情形下是怎么具体使用的. service 你可以理解成没 ...

  3. Android中的跨进程通信方法实例及特点分析(一):AIDL Service

    转载请注明出处:http://blog.csdn.net/bettarwang/article/details/40947481 近期有一个需求就是往程序中增加大数据的採集点,可是由于我们的Andro ...

  4. 跨进程调用Service(AIDL Service)

    1.什么是aidl:aidl这是 Android Interface definition language的缩写,一看就明确.它是一种android内部进程通信接口的描写叙述语言.通过它我们能够定义 ...

  5. Android service binder aidl 关系

    /********************************************************************************** * Android servic ...

  6. 图解Android - Binder 和 Service

    在 Zygote启动过程 一文中我们说道,Zygote一生中最重要的一件事就是生下了 System Server 这个大儿子,System Server 担负着提供系统 Service的重任,在深入了 ...

  7. AIDL Service Android进程间通信机制

    转载出处:http://www.apkbus.com/home.php?mod=space&do=blog&uid=664680&id=59465 我们知道,在Android ...

  8. Android 核心分析 之六 IPC框架分析 Binder,Service,Service manager

    IPC框架分析 Binder,Service,Service manager 我首先从宏观的角度观察Binder,Service,Service Manager,并阐述各自的概念.从Linux的概念空 ...

  9. Android AIDL SERVICE 双向通信 详解

    http://www.cnblogs.com/punkisnotdead/p/5062631.html 起因 是这个blog 提到了 用webview 的时候 用开启子进程的方式 可以极大避免内存泄露 ...

随机推荐

  1. Release Python Program as exe

    py2exe 可以用来将python program 以exe的形式发布. 安装py2exe 对于python 3.x pip install py2exe 可以直接安装 对于python 2.7, ...

  2. php函数之数组

    关联数组 isset bool isset( mixed $val [, mix $...]) 变量是否已设置并且非null.多个参数从左到右计算. 判断null $a=null;var_dump(i ...

  3. php 快速导出大量CSV文件

    原文链接 https://segmentfault.com/a/1190000005366832 /** * 导出excel(csv) * @data 导出数据 * @headlist 第一行,列名 ...

  4. MySQL存储过程中一直困扰的 の 变量中的@

    在声明变量中CREATE function Get_StrArrayLength ( @str varchar(1024), --要分割的字符串@split varchar(10) --分隔符号)re ...

  5. 主题:学习Spring必学的Java基础知识(9)----HTTP报文

    转: 引述要学习Spring框架的技术内幕,必须事先掌握一些基本的Java知识,正所谓“登高必自卑,涉远必自迩”.以下几项Java知识和Spring框架息息相关,不可不学(我将通过一个系列分别介绍这些 ...

  6. 实现List集合中数据逆序排列

    Collections.reverse(list); 实现list集合逆序排列

  7. php面向对象(设计模式 工厂模式)

    //设计模式//单例模式//类的计划生育//让该类在外界无法造成对象//让外界可以造一个对象,做一个静态方法返回对象//在累里面可以通过静态变量控制返回对象只能有一个 //class Cat//{// ...

  8. UITableView点击背景

    系统自定义的点击背景有时间觉得效果不好想换个 - (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelect ...

  9. HDU 4578 线段树复杂题

    题目大意: 题意:有一个序列,有四种操作: 1:区间[l,r]内的数全部加c. 2:区间[l,r]内的数全部乘c. 3:区间[l,r]内的数全部初始为c. 4:询问区间[l,r]内所有数的P次方之和. ...

  10. 【Floyd最短路】第七届福建省赛 FZU Problem 2271 X

    http://acm.fzu.edu.cn/problem.php?pid=2271 [题意] 给定一个n个点和m条边的无向连通图,问最多可以删去多少条边,使得每两个点之间的距离(最短路长度)不变. ...