Android跨进程通信之AIDL(四)
16lz
2021-12-04
目录
Android跨进程通信之小例子(一)
Android跨进程通信之非AIDL(二)
Android跨进程通信之Proxy与Stub(三)
Android跨进程通信之AIDL(四)
什么是AIDL
从该系列的几篇文章里,我们知道了
Proxy和Stub模式
。其实跨进程通信
中所谓的AIDL就是帮我们去实现Proxy和Stub模式
,帮我们封装好编码
和译码
功能。底层还是transact
和onTransact
方法的调用。
小例子
做一个经典的Echo程序。程序向服务发送一句话,服务给打印出来。
第一步:定义AIDL接口文件(提供Service的APP)
你的服务提供哪些接口去让别人使用,你要先说清楚,但是此时并不需要给出实现。
- 新建
com.example.aidlechoservice.aidl
包 - 新建一个普通文件,命名为
IEchoService.aidl
package com.example.aidlechoservice.aidl;//这里是当前文件所在包名interface IEchoService{ String echo(String inStr);}
如果使用Eclipse的话,这样定义之后我们会看到产生了
gen/com.example.aidlechoservice.aidl/IEchoService.java
文件
第二步:实现服务端的Stub(提供Service的APP)
超级简单,就一句话。
IEchoService.Stub mBinder = new IEchoService.Stub() { @Override public String echo(String inStr) throws RemoteException { return "echo " + inStr + " at " + sdf.format(new Date()); } };
所以整体代码就这样
public class EchoService extends Service { private IEchoService.Stub mBinder; private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public void onCreate() { super.onCreate(); mBinder = new IEchoService.Stub() { @Override public String echo(String inStr) throws RemoteException { return "echo " + inStr + " at " + sdf.format(new Date()); } }; } @Override public IBinder onBind(Intent intent) { return mBinder; } }
第三步:编写APP的AIDL(调用Service的APP)
跟上面服务的是一模一样,必须是一模一样,否则就不行。
第四步:实现客户端的Proxy(调用Service的APP)
很简单,还是一句话搞定
IEchoService mService = IEchoService.Stub.asInterface(binder);
布局
代码
public class MainActivity extends Activity { private IEchoService mService; private ServiceConnection mServiceConnection; private Intent mServiceIntent = new Intent(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mServiceIntent.setComponent( new ComponentName("com.example.aidlechoservice", "com.example.aidlechoservice.service.EchoService")); mServiceConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name, IBinder binder) { mService = IEchoService.Stub.asInterface(binder); } }; } public void bind(View v) { if (isBinded()) { return; } bindService(mServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE); } public void unbind(View v) { if (!isBinded()) { return; } unbindService(mServiceConnection); } public void echo(View v) { if (!isBinded()) { return; } try { String result = mService.echo("Hello world!!!"); Log.i("TAG", result); } catch (RemoteException e) { e.printStackTrace(); } } private boolean isBinded() { return mService != null; }}
项目地址
Github地址
更多相关文章
- Android(安卓)滑动效果高级篇(七)—— 华丽翻页效果
- Android异步处理
- Android异步处理系列文章索引
- Android(安卓)Push Notification技术实现
- RelativeLayout属性和使用, 实现上面view叠加在下面view之上的效
- pc 与 android webrtc 通信的研究
- android 流量统计实现思路
- Android实现简易版弹钢琴效果
- Android仿人人客户端(v5.7.1)——欢迎和导引界面的编码实现