评论

收藏

[Android] Android下的IPC通信方式

移动开发 移动开发 发布于:2022-04-13 15:36 | 阅读数:397 | 评论:0

一、Bundle
Android的Activity、Service、Receiver都支持在Intent传递Bundle数据,Bundle实现了Parcelable接口,
所以能很方便的在不同进程之间进行数据传传输.比如A应用打开B应用的某个Activity,如果要传递自定义的类型,
可以继承自Parcelable接口,参考Parcelable的使用方式 Android序列化的几种实现方式
A页面:
public class MainActivity extends AppCompatActivity {
  private final static int OPEN_OTHER_ACTIVITY_REQUEST_CODE = 0;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
String packageName = "komine.demos.ipcdemo2";
String activityName = packageName + ".MainActivity";
intent.putExtra("msg","来自komine.demos.ipc传递的参数");
ComponentName componentName = new ComponentName(packageName,activityName);
intent.setComponent(componentName);
startActivityForResult(intent,OPEN_OTHER_ACTIVITY_REQUEST_CODE);
  }
  
  @Override
  protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if(data != null){
      if(requestCode == OPEN_OTHER_ACTIVITY_REQUEST_CODE){
        Toast.makeText(getApplicationContext(),data.getStringExtra("value"),Toast.LENGTH_SHORT).show();
      }
    }
  }
}
B页面:
public class MainActivity extends AppCompatActivity {
  private final static int RESULT_CODE = 0;
  private TextView textView;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.tv);
    if(getIntent() != null){
      String msg = getIntent().getStringExtra("msg");
      textView.setText(msg);
    }
  }
  @Override
  public void onBackPressed() {
     Intent intent = new Intent();
     intent.putExtra("value","来自komine.demos.ipcdemo2的MainActivity页面返回的值");
     setResult(RESULT_CODE,intent);
     finish();
  }
}
DSC0000.png

二、Messenger
1.基本使用
Messenger是基于AIDL的一种轻量化跨进程通信方式,内部是通过Handler进行消息发送的
首先新建一个MessengerService类
public class MessengerService extends Service implements Handler.Callback {
  private static final String TAG = "MessengerService";
  public static final int CLIENT_WHAT = 1;
  public static final int SERVER_WHAT = 2;
  //服务端接收到一条消息就会向客户端发送一条回复消息
  @Override
  public boolean handleMessage(@NonNull Message msg) {
    if (msg.what == CLIENT_WHAT) {
      Log.d(TAG, "收到来自客户端的消息:" + msg.getData());
  //msg.replyTo是客户端定义的Messenger对象,用来向客户端发送消息
  Messenger client = msg.replyTo;
      Message replyMessage = Message.obtain(null, SERVER_WHAT);
  Bundle bundle = new Bundle();
  bundle.putString("reply", "服务端回复客户端的数据..." + new Date());
  replyMessage.setData(bundle);
      try {
//调用客户端的Messenger对象向客户端发送消息
        client.send(replyMessage);
  } catch (Exception e) {
        e.printStackTrace();
  }
    }
    return false;
  }
  //服务端的Messenger对象,客户端可以通过onBind中返回的IBinder对象
  //来实例化一个Messenger对象,用来向服务端发送Message,Messenger内部采用
  //的是Message来进行消息传递,所以需要一个Handler对象来进行消息发送
  private final Messenger mMessenger = new Messenger(new Handler(Looper.getMainLooper(),this));
  @Nullable
  @Override
  public IBinder onBind(Intent intent) {
//返回Messenger的Binder对象
    return mMessenger.getBinder();
  }
}
在AndroidManifest.xml注册MessengerService,该服务运行在另外一个进程中,冒号开头表示在当前进程名之前加上完整的包名,
并且该进程为应用的私有进程,不以冒号开头,则表示全局进程,其他可以通过sharedUserId的方式将自己运行在同一个进程中,比如
sharedUserId = "android.uid.system",将自己运行在系统进程中,以取得系统进程的一些权限,以这种方式运行在一起的进程之间
可以互相访问对方的私有数据,比如data目录、files目录,另外签名要保持一致才行,debug版本不需要.
DSC0001.png

注册MessengerService
<service android:name="komine.demos.messager.MessengerService" android:process=":remote"/>
MainActivity,布局就一个按钮,绑定了sendMsg方法就不贴代码了
public class MainActivity extends AppCompatActivity implements ServiceConnection,Handler.Callback {
  private Messenger mService;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
//绑定远程Service
bindService(new Intent(this, MessengerService.class),this,Context.BIND_AUTO_CREATE);
  }
  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
    //通过IBinder对象创建一个Messenger实例
mService = new Messenger(service);
  }
  //点击发送按钮就会向服务端发送一条Message
  public void sendMsg(View view) {
    Message msg = Message.obtain(null,MessengerService.CLIENT_WHAT);
Bundle data = new Bundle();
data.putString("msg","hello,this is client");
msg.setData(data);
//指定当前消息是那个Messenger对象发送的,该对象就是我们在服务端
//向客户端发送Message的Messenger对象
msg.replyTo = mGetReplyMessenger;
    try{
      mService.send(msg);
}catch (RemoteException e){
      e.printStackTrace();
}
  }
  @Override
  public void onServiceDisconnected(ComponentName name) {
  }
  //客户端的Messenger对象
  private Messenger mGetReplyMessenger = new Messenger(new Handler(Looper.getMainLooper(),this));
  //处理服务端发送回来的Message
  @Override
  public boolean handleMessage(@NonNull Message msg) {
    if(msg.what == MessengerService.SERVER_WHAT){
      Log.d("client", "收到来自服务端的消息:" + msg.getData().getString("reply"));
  }
    return false;
  }
  @Override
  protected void onDestroy() {
    super.onDestroy();
    if(mService != null && mService.getBinder().isBinderAlive()){
      unbindService(this);
}
  }
}
客户端输出:
DSC0002.png

服务端输出:
DSC0003.png
注意:由于MessengerService是在不同的线程,需要切换进程才能看到对于的日志输出
Messenger是通过Handler来实现消息发送的,而Handler的内部是通过消息队列来维护每一个Message对象,
队列是一个先进先出的数据结构,所以Messenger无法并发处理多个消息,只能一条一条的处理.
2.绑定其他应用的Service
上述代码是客户端和服务端都在同一个应用之内的两个不同进程,如果要绑定其他应用的xxx服务,需要通过显式Intent来绑定,
并且远程Service要设置 exported = "true",不然会抛异常
<service android:name=".MessengerServer" android:exported="true"/>
a.setClassName()方式
intent.setClassName("包名","包名.Service名称");
b.setComponent() 方式
intent.setComponent(new ComponentName("包名","包名.Service名称"));
例如:
Intent intent = new Intent();
intent.setComponent(new ComponentName("komine.demos.messenegerserver","komine.demos.messenegerserver.MessengerServer"));
//网上有说直接在bindService()之前调用startService()开启服务,我试过是无效的,小米Note4x(7.1)可以
//在调用该方法之前,需要在另一端(要绑定的服务所在的应用)开启对应的Service
//测试环境:模拟器和真机(索尼),Android11必要在对应应用开启Service才能绑定成功
bindService(intent, this, Context.BIND_AUTO_CREATE);
注意:在在调用bindService()之前,需要远程进程(指要绑定的服务所在的应用)开启要绑定的Service,
不然bindService()不报错,也不会回调onServiceConnected()
三、AIDL
AIDL是Android 接口定义语言,可以通过AIDL在两个进程之间进行IPC通信.
1.基本使用
新建Game.java
public class Game implements Parcelable {
  public String name;
  public Game(String name){
    this.name = name;
  }
  protected Game(Parcel in) {
    name = in.readString();
  }
  public static final Creator<Game> CREATOR = new Creator<Game>() {
    @Override
public Game createFromParcel(Parcel in) {
      return new Game(in);
    }
    @Override
public Game[] newArray(int size) {
      return new Game[size];
}
  };
  @Override
  public int describeContents() {
    return 0;
  }
  @Override
  public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(name);
  }
}
新建Game.aidl
可能会提示名称不唯一的错误,不让创建,可以先随便取个名字,然后再重命名,应该是as的bug
DSC0004.png

Game.aidl 对应 Game.java
// Game.aidl
package komine.demos.ipcdemo3;
// Declare any non-default types here with import statements
//指向Game.java
parcelable Game;
新建IGameShopManager.aidl
// IGameShopManager.aidl
package komine.demos.ipcdemo3;
// Declare any non-default types here with import statements
//引入Game.aild 即使是在同一包名下也需要import
import komine.demos.ipcdemo3.Game;
import komine.demos.ipcdemo3.IDownloadCompleteListener;
interface IGameShopManager {
  boolean buy(float money);
  void download(in IDownloadCompleteListener listener);
  void registerDownloadListener(in IDownloadCompleteListener listener);
  void unregisterDownloadListener(in IDownloadCompleteListener listener);
}
新建IDownloadCompleteListener.aidl
// IDownloadCompleteListener.aidl
package komine.demos.ipcdemo3;
// Declare any non-default types here with import statements
import komine.demos.ipcdemo3.Game;
interface IDownloadCompleteListener {
  void onDownloadCompleted(in Game game);
}
DSC0005.png

新建EShopManagerService.java
public class EShopManagerService extends Service {
  //Android提供的用于跨进程删除listener的接口,内部维护了一个Map集合,key是IBinder,通过
  //比对key来删除对应的listener,如果不使用这个类,而使用普通的集合,在服务解绑,页面关闭之后,listener也不会
  //移除,可以在循环中不断回调打印日志试试
  private RemoteCallbackList<IDownloadCompleteListener> listeners = new RemoteCallbackList<>();
  private Binder mBinder = new IGameShopManager.Stub() {
    @Override
public boolean buy(float money) throws RemoteException {
      return money >= 100;
    }
    @Override
public void download(IDownloadCompleteListener listener) throws RemoteException {
      Game game = new Game("黑暗之魂重置版");
      try {
        //模拟耗时操作
Thread.sleep(3000);
//固定写法,从RemoteCallbackList取数据的固定写法
listeners.beginBroadcast();
        int size = listeners.getRegisteredCallbackCount();
        for (int i = 0;i < size;i++){
          //Android26+可以使用getRegisteredCallbackItem()方法直接获取
          listeners.getBroadcastItem(i).onDownloadCompleted(game);
    }
        //固定写法
listeners.finishBroadcast();
   } catch (InterruptedException e) {
        e.printStackTrace();
   }
    }
    @Override
public void registerDownloadListener(IDownloadCompleteListener listener) throws RemoteException {
  //注册回调接口
      listeners.register(listener);
}
    @Override
public void unregisterDownloadListener(IDownloadCompleteListener listener) throws RemoteException {
  //移除回调接口
      listeners.unregister(listener);
}
  };
  @Nullable
  @Override
  public IBinder onBind(Intent intent) {
    return mBinder;
  }
}
注册EShopManagerService
<service android:name=".EShopManagerService" android:process=":remote"/>
MainActivity.java
public class MainActivity extends AppCompatActivity implements ServiceConnection {
  private IGameShopManager mShopManager;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindService(new Intent(this,EShopManagerService.class),this, Context.BIND_AUTO_CREATE);
  }
  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
    mShopManager = IGameShopManager.Stub.asInterface(service);
    try {
  //注册回调接口
      mShopManager.registerDownloadListener(downloadCompleteListener);
} catch (RemoteException e) {
      e.printStackTrace();
}
  }
  @Override
  public void onServiceDisconnected(ComponentName name) {
  }
  public void buy(View view) throws RemoteException {
    boolean buyResult = mShopManager.buy(100);
    if(buyResult){
      Toast.makeText(getApplicationContext(),"购买成功!",Toast.LENGTH_SHORT).show();
}
  }
  public void download(View view) {
    try{
      mShopManager.download(downloadCompleteListener);
}catch (Exception e){
      e.printStackTrace();
}
  }
  private IDownloadCompleteListener downloadCompleteListener = new IDownloadCompleteListener.Stub() {
    @Override
public void onDownloadCompleted(final Game game) throws RemoteException {
      runOnUiThread(new Runnable() {
        @Override
public void run() {
          Toast.makeText(getApplicationContext(),"下载完成:" + game.name,Toast.LENGTH_SHORT).show();
}
      });
}
  };
  @Override
  protected void onDestroy() {
    super.onDestroy();
//如果mShopManager的Binder未被销毁
    if(mShopManager != null && mShopManager.asBinder().isBinderAlive()){
      unbindService(this);
      try {
        mShopManager.unregisterDownloadListener(downloadCompleteListener);
  } catch (RemoteException e) {
        e.printStackTrace();
  }
    }
  }
}
DSC0006.png

---------------------------------2022-04-09 更新----------------------------------
2.AIDL绑定远程服务
绑定过程跟Messenger绑定远程服务是一致的.
首先将前面生成好的aidl文件夹全部拷贝到另一个app(服务端)中,直接复制main/aidl文件夹,粘贴就好了
DSC0007.png

注意:客户端的aidl 文件夹的包名要和服务端的aidl包名一致,复制后会报错,需要build生成所需的文件.
然后将之前创建的EShopManagerService.java复制到app下的(服务端0)MainActivity同级目录下,
在AndroidManifest.xml中注册服务
<service android:name=".EShopManagerService" android:exported="true"/>
然后通过显式Intent绑定到远程Service
客户端绑定服务端Service
Intent intent = new Intent();
intent.setComponent(new ComponentName("包名(应用的包名)","(Service所在文件的包名).服务名称"));
bindService(intent,this, Context.BIND_AUTO_CREATE);
由于是复制粘贴的,包名有可能填错,最不会出错的办法是直接去Service文件的最上方复制package后面的包名
3.AIDL权限验证
默认情况下,我们创建的服务任何人都能绑定,只要知道包名和服务的名称就可以连接,
那么如何添加权限验证呢
a.在Service的onBind()方法中验证,只要return null,验证失败的客户端就无法绑定服务
@Nullable
@Override
public IBinder onBind(Intent intent) {
  Boolean noAuthorized = true;
  ...
  ...
  //至于验证方式有很多,比如在AndroidManifest.xml中自定义permission,然后判断是否有声明这个权限
  //调用checkCallingOrSelfPermission()检查是否有权限
  if(!noAuthorized){
    return null;
  }
  return mBinder;
}
服务端AndroidManifest.xml
//申明一个连接到远程Service所需的自定义权限
<permission android:name="komine.demos.messenegerserver.EShopManagerService"/>
...
...
//在Service上指定android:permission:komine.demos.messenegerserver.EShopManagerService
<service android:name="komine.demos.ipcdemo3.EShopManagerService" android:exported="true" android:permission="komine.demos.messenegerserver.EShopManagerService"/>
客户端必须显式声明这个权限,不然会抛权限拒绝的异常
客户端AndroidManifest.xml
//komine.demos.messenegerserver.EShopManagerService 在服务端申明的自定义权限
<uses-permission android:name="komine.demos.messenegerserver.EShopManagerService"/>
b.在服务端的onTransact()验证
在Service中重写onTransact()方法,然后进行验证
private Binder mBinder = new IGameShopManager.Stub() {
  ...
  ...
  @Override
  public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
//验证方式按自己需求进行选择,返回false表示验证失败
    return super.onTransact(code, data, reply, flags);
}
四、ContentProvider
ContentProvider是Android中提供用于不同应用之间进行数据共享的方式.
1.基本使用
使用很简单,只需要新建一个类继承自ContentProvider即可
public class MyContentProvider extends ContentProvider {
  private final static String TAG = "MyContentProvider";
  @Override
  public boolean onCreate() {
    Log.d(TAG,"onCreate...");
    return false;
  }
  @Nullable
  @Override
  public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection,   @Nullable String[] selectionArgs, @Nullable String sortOrder) {
    Log.d(TAG,"query " + Thread.currentThread().getName());
    return null;
  }
  @Nullable
  @Override
  public String getType(@NonNull Uri uri) {
    return "getType";
  }
  @Nullable
  @Override
  public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
    Log.d(TAG,"insert" + Thread.currentThread().getName());
    return null;
  }
  @Override
  public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
    Log.d(TAG,"delete" + Thread.currentThread().getName());
    return 0;
  }
  @Override
  public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
    Log.d(TAG,"update" + Thread.currentThread().getName());
    return 0;
  }
}
然后在AndroidManifest.xml的application标签下注册
<provider
  android:authorities="komine.demos.ipcdemo4.provider"
  android:exported="true"
  android:name=".MyContentProvider"/>
接下来就能在其他应用中访问
public class MainActivity extends AppCompatActivity{
  private Messenger mService;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//authorities:其他应用的provider中定义的authorities值
//uri = content:// + authorities
Uri uri = Uri.parse("content://komine.demos.ipcdemo4.provider");
getContentResolver().query(uri,null,null,null,null);
getContentResolver().insert(uri,null);
getContentResolver().delete(uri,null,null);
getContentResolver().update(uri,null,null,null);
  }
}
DSC0008.png

Android11+ 更改了应用之间交互的方式,需要在AndroidManifest.xml中添加queries标签,然后在其中添加目标应用的包名,才能访问到目标应用提供的ContentProvider.
放在manifest节点
<queries>
  <package android:name="komine.demos.ipcdemo4" />
</queries>

   
   
   
                        

关注下面的标签,发现更多相似文章