android aidl进程间的通信

2024-06-04 21:38
文章标签 android 进程 通信 aidl

本文主要是介绍android aidl进程间的通信,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、IPC是Inter-Process Communication的缩写,含义就是进程间通信或者跨进程通信,是指两个进程之间进行数据交换的过程。进程在PC和移动设备上指的是一个程序或者一个应用。一个进程可以包含多个线程,因此进程和线程是包含被包含的关系。这里主要是实现activity通过aidl调用service方法和一个应用调用另一个应用方法的实现。

2、aidl在应用间的使用


首先可以先实现 .aidl文件,.aidl文件可以直接新建,跟java同级

// IMyAidlInterface.aidl
package com.example.apple.myfragment;// Declare any non-default types here with import statementsinterface IMyAidlInterface {/*** Demonstrates some basic types that you can use as parameters* and return values in AIDL.*/int add(int a, int b);int reduce(int a,int b);
}
这里只写两个方法,add和reduce,这里通过aidl将service和activity绑定,这样可以实现activity对service里面的方法的调用,要让service支持绑定,需要实现onBind方法,并反回被绑定service的当前实例。需要注意的是更新完。aidl文件需要刷新一下工程,service代码如下所示:

package com.example.apple.myfragment;import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;/*** Created by apple on 17/4/14.*/public class MyService extends Service {@Nullable@Overridepublic IBinder onBind(Intent intent) {return myAidlInterface;}private final IMyAidlInterface.Stub myAidlInterface = new IMyAidlInterface.Stub() {@Overridepublic int add(int a, int b) throws RemoteException {Log.e("nsc","a+b="+(a+b));return a+b;}@Overridepublic int reduce(int a, int b) throws RemoteException {Log.e("nsc","a-b="+(a-b));return rd(a,b);}};private int rd(int a ,int b){if (a>b){return a-b;}else {return b-a;}}
}

service和activity连接需要使用ServiceConnection,里面实现了两个方法,连接和断开连接。建立连接后就可以对service实例进行引用了,当建立连接需要调用aidlInterface = IMyAidlInterface.Stub.asInterface(service);如下所示,使用完还要在onDestroy里调用unbindService(connection);

package com.example.apple.myfragment;import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;public class MainActivity extends AppCompatActivity {private Button btnAdd;private Button btnReduce;private TextView tvResult;private IMyAidlInterface aidlInterface;private ServiceConnection connection = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {aidlInterface = IMyAidlInterface.Stub.asInterface(service);}/*** 断开连接* @param name*/@Overridepublic void onServiceDisconnected(ComponentName name) {aidlInterface = null;}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();bindAndStartService();}/*** 绑定服务*/private void bindAndStartService() {Intent intent = new Intent(this, MyService.class);intent.setAction("com.example.apple.myfragment");bindService(intent, connection, Context.BIND_AUTO_CREATE);startService(intent);}private void initView() {tvResult = (TextView)findViewById(R.id.tv_result);btnAdd = (Button)findViewById(R.id.btn_add);btnAdd.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {try {if (aidlInterface!=null){tvResult.setText(aidlInterface.add(3,4)+"");}}catch (Exception e){e.printStackTrace();}}});btnReduce = (Button)findViewById(R.id.btn_reduce);btnReduce.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {try {if (aidlInterface!=null){tvResult.setText(aidlInterface.reduce(5,3)+"");}}catch (Exception e){e.printStackTrace();}}});}@Overrideprotected void onDestroy() {unbindService(connection);super.onDestroy();}
}
还要在manifest里面配置一下
<service android:name=".MyService"><intent-filter><action android:name="com.example.apple.myfragment"></action><category android:name="android.intent.category.DEFAULT"/></intent-filter></service>

最后记得在build.gradl里面的android{}加入下面代码,以便实现对.aidl文件的调用。

sourceSets {main {java.srcDirs = ['src/main/java', 'src/main/aidl']}}

实现效果


3、这里是activity调用service方法的实现。下面实现一下不同应用间的通信实现。上面的实现算是服务端,下面实现一下客户端代码


客户端的.aidl 文件直接拷贝服务端的就可以,保持好同样的路径,代码中实现需要注意的是在5.0以上的系统中启动服务需要用setPackage,否则报错,填写是服务端的包名,其他没什么注意的了。详细可以看下面代码:

 /*** 绑定服务*/private void bindAndStartService() {Intent intent = new Intent();intent.setAction("com.example.apple.myfragment");intent.setPackage("com.example.apple.myfragment");bindService(intent, connection, Context.BIND_ABOVE_CLIENT);}
MainActivity代码实现

package com.example.apple.aidl;import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;import com.example.apple.aidlactivity.R;
import com.example.apple.myfragment.IMyAidlInterface;public class MainActivity extends AppCompatActivity {private Button btnAdd;private Button btnReduce;private TextView tvResult;private IMyAidlInterface aidlInterface;private ServiceConnection connection = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {aidlInterface = IMyAidlInterface.Stub.asInterface(service);}/*** 断开连接* @param name*/@Overridepublic void onServiceDisconnected(ComponentName name) {aidlInterface = null;}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();bindAndStartService();}/*** 绑定服务*/private void bindAndStartService() {Intent intent = new Intent();intent.setAction("com.example.apple.myfragment");intent.setPackage("com.example.apple.myfragment");bindService(intent, connection, Context.BIND_ABOVE_CLIENT);}private void initView() {tvResult = (TextView)findViewById(R.id.tv_result);btnAdd = (Button)findViewById(R.id.btn_add);btnAdd.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {//   bindAndStartService();try {//  if (aidlInterface!=null){tvResult.setText(aidlInterface.add(3,4)+"");//  }}catch (Exception e){e.printStackTrace();}}});btnReduce = (Button)findViewById(R.id.btn_reduce);btnReduce.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {try {if (aidlInterface!=null){tvResult.setText(aidlInterface.reduce(5,3)+"");}}catch (Exception e){e.printStackTrace();}}});}@Overrideprotected void onDestroy() {unbindService(connection);super.onDestroy();}
}

4、了解一下IMyAidlInterface里面的代码,就是服务端和客户端是如何建立关联的。服务端提供的服务是由IMyAidlInterface.Stub来执行,Stub这个类是Binder的子类,继承了binder的,而且mBinder实现了IMyAidlInterface接口的方法。

public interface IMyAidlInterface extends android.os.IInterface {/*** Local-side IPC implementation stub class.*/public static abstract class Stub extends android.os.Binder implements com.example.apple.myfragment.IMyAidlInterface {private static final java.lang.String DESCRIPTOR = "com.example.apple.myfragment.IMyAidlInterface";

我们在.aidl文件里面添加的两个方法在这里都可以看到

 @Overridepublic int add(int a, int b) throws android.os.RemoteException {android.os.Parcel _data = android.os.Parcel.obtain();android.os.Parcel _reply = android.os.Parcel.obtain();int _result;try {_data.writeInterfaceToken(DESCRIPTOR);_data.writeInt(a);_data.writeInt(b);mRemote.transact(Stub.TRANSACTION_add, _data, _reply, 0);_reply.readException();_result = _reply.readInt();} finally {_reply.recycle();_data.recycle();}return _result;}@Overridepublic int reduce(int a, int b) throws android.os.RemoteException {android.os.Parcel _data = android.os.Parcel.obtain();android.os.Parcel _reply = android.os.Parcel.obtain();int _result;try {_data.writeInterfaceToken(DESCRIPTOR);_data.writeInt(a);_data.writeInt(b);mRemote.transact(Stub.TRANSACTION_reduce, _data, _reply, 0);_reply.readException();_result = _reply.readInt();} finally {_reply.recycle();_data.recycle();}return _result;}}

这个proxy实例传入了我们的binder驱动,并且封装了我们调用服务端的代码,客户端通过Binder驱动的transact()方法调用服务端代码。

首先声明两个parce对象,一个用于传递数据,一个用于接收返回的数据。与服务端的enforceInterfac对应。

_data.writeInterfaceToken(DESCRIPTOR);_data.writeInt(a);_data.writeInt(b);
写入需要传递的数据。

mRemote.transact(Stub.TRANSACTION_reduce, _data, _reply, 0);

最后读出我们服务端返回的数据,然后return。可以看到和服务端的onTransact基本是一行一行对应的。

/** This file is auto-generated.  DO NOT MODIFY.* Original file: /Users/apple/Desktop/MyFragment/app/src/main/aidl/com/example/apple/myfragment/IMyAidlInterface.aidl*/
package com.example.apple.myfragment;
// Declare any non-default types here with import statementspublic interface IMyAidlInterface extends android.os.IInterface {/*** Local-side IPC implementation stub class.*/public static abstract class Stub extends android.os.Binder implements com.example.apple.myfragment.IMyAidlInterface {private static final java.lang.String DESCRIPTOR = "com.example.apple.myfragment.IMyAidlInterface";/*** Construct the stub at attach it to the interface.*/public Stub() {this.attachInterface(this, DESCRIPTOR);}/*** Cast an IBinder object into an com.example.apple.myfragment.IMyAidlInterface interface,* generating a proxy if needed.*/public static com.example.apple.myfragment.IMyAidlInterface asInterface(android.os.IBinder obj) {if ((obj == null)) {return null;}android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);if (((iin != null) && (iin instanceof com.example.apple.myfragment.IMyAidlInterface))) {return ((com.example.apple.myfragment.IMyAidlInterface) iin);}return new com.example.apple.myfragment.IMyAidlInterface.Stub.Proxy(obj);}@Overridepublic android.os.IBinder asBinder() {return this;}@Overridepublic boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException {switch (code) {case INTERFACE_TRANSACTION: {reply.writeString(DESCRIPTOR);return true;}case TRANSACTION_add: {data.enforceInterface(DESCRIPTOR);int _arg0;_arg0 = data.readInt();int _arg1;_arg1 = data.readInt();int _result = this.add(_arg0, _arg1);reply.writeNoException();reply.writeInt(_result);return true;}case TRANSACTION_reduce: {data.enforceInterface(DESCRIPTOR);int _arg0;_arg0 = data.readInt();int _arg1;_arg1 = data.readInt();int _result = this.reduce(_arg0, _arg1);reply.writeNoException();reply.writeInt(_result);return true;}}return super.onTransact(code, data, reply, flags);}private static class Proxy implements com.example.apple.myfragment.IMyAidlInterface {private android.os.IBinder mRemote;Proxy(android.os.IBinder remote) {mRemote = remote;}@Overridepublic android.os.IBinder asBinder() {return mRemote;}public java.lang.String getInterfaceDescriptor() {return DESCRIPTOR;}@Overridepublic int add(int a, int b) throws android.os.RemoteException {android.os.Parcel _data = android.os.Parcel.obtain();android.os.Parcel _reply = android.os.Parcel.obtain();int _result;try {_data.writeInterfaceToken(DESCRIPTOR);_data.writeInt(a);_data.writeInt(b);mRemote.transact(Stub.TRANSACTION_add, _data, _reply, 0);_reply.readException();_result = _reply.readInt();} finally {_reply.recycle();_data.recycle();}return _result;}@Overridepublic int reduce(int a, int b) throws android.os.RemoteException {android.os.Parcel _data = android.os.Parcel.obtain();android.os.Parcel _reply = android.os.Parcel.obtain();int _result;try {_data.writeInterfaceToken(DESCRIPTOR);_data.writeInt(a);_data.writeInt(b);mRemote.transact(Stub.TRANSACTION_reduce, _data, _reply, 0);_reply.readException();_result = _reply.readInt();} finally {_reply.recycle();_data.recycle();}return _result;}}static final int TRANSACTION_add = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);static final int TRANSACTION_reduce = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);}public int add(int a, int b) throws android.os.RemoteException;public int reduce(int a, int b) throws android.os.RemoteException;
}
代码下载地址: http://download.csdn.net/detail/u011324501/9817169









































这篇关于android aidl进程间的通信的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1031195

相关文章

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.

Java进程异常故障定位及排查过程

《Java进程异常故障定位及排查过程》:本文主要介绍Java进程异常故障定位及排查过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、故障发现与初步判断1. 监控系统告警2. 日志初步分析二、核心排查工具与步骤1. 进程状态检查2. CPU 飙升问题3. 内存

Android DataBinding 与 MVVM使用详解

《AndroidDataBinding与MVVM使用详解》本文介绍AndroidDataBinding库,其通过绑定UI组件与数据源实现自动更新,支持双向绑定和逻辑运算,减少模板代码,结合MV... 目录一、DataBinding 核心概念二、配置与基础使用1. 启用 DataBinding 2. 基础布局

Android ViewBinding使用流程

《AndroidViewBinding使用流程》AndroidViewBinding是Jetpack组件,替代findViewById,提供类型安全、空安全和编译时检查,代码简洁且性能优化,相比Da... 目录一、核心概念二、ViewBinding优点三、使用流程1. 启用 ViewBinding (模块级

Windows的CMD窗口如何查看并杀死nginx进程

《Windows的CMD窗口如何查看并杀死nginx进程》:本文主要介绍Windows的CMD窗口如何查看并杀死nginx进程问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录Windows的CMD窗口查看并杀死nginx进程开启nginx查看nginx进程停止nginx服务

Java进程CPU使用率过高排查步骤详细讲解

《Java进程CPU使用率过高排查步骤详细讲解》:本文主要介绍Java进程CPU使用率过高排查的相关资料,针对Java进程CPU使用率高的问题,我们可以遵循以下步骤进行排查和优化,文中通过代码介绍... 目录前言一、初步定位问题1.1 确认进程状态1.2 确定Java进程ID1.3 快速生成线程堆栈二、分析

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

RabbitMQ工作模式中的RPC通信模式详解

《RabbitMQ工作模式中的RPC通信模式详解》在RabbitMQ中,RPC模式通过消息队列实现远程调用功能,这篇文章给大家介绍RabbitMQ工作模式之RPC通信模式,感兴趣的朋友一起看看吧... 目录RPC通信模式概述工作流程代码案例引入依赖常量类编写客户端代码编写服务端代码RPC通信模式概述在R

在Spring Boot中实现HTTPS加密通信及常见问题排查

《在SpringBoot中实现HTTPS加密通信及常见问题排查》HTTPS是HTTP的安全版本,通过SSL/TLS协议为通讯提供加密、身份验证和数据完整性保护,下面通过本文给大家介绍在SpringB... 目录一、HTTPS核心原理1.加密流程概述2.加密技术组合二、证书体系详解1、证书类型对比2. 证书获

Python模拟串口通信的示例详解

《Python模拟串口通信的示例详解》pySerial是Python中用于操作串口的第三方模块,它支持Windows、Linux、OSX、BSD等多个平台,下面我们就来看看Python如何使用pySe... 目录1.win 下载虚www.chinasem.cn拟串口2、确定串口号3、配置串口4、串口通信示例5