AIDL实践一:基本数据类型的跨进程序运算
本文是慕课网视频的练习,视频网址:http://www.imooc.com/learn/606
- 开发工具: Android Studio
- 功能: 实现跨进程的加法计算
一.编写服务端:
- 创建项目
- 在java目录同级下创建aidl文件夹,IAddAidl.aidl文件,文件内容如下:
// IAddAidl.aidl
package com.lyj.aidldemo;
// Declare any non-default types here with import statements
interface IAddAidl {
int add(int num1,int num2);
}
可以看到,我们在IAddAidl.aidl中定义了一个接口,里面的方法是两个数字做加法运算
写完之后,clean一下
3. 在Java目录下创建远程服务MyService,代码如下
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return iBinder;
}
private IBinder iBinder = new IAddAidl.Stub() {
@Override
public int add(int num1, int num2) throws RemoteException {
return (num1 + num2);
}
};
}
在这个类中,实现了IAddAidl中的方法,在客户端绑定服务的时候,返回iBinder
在Manifest中注册:
<service android:name=".MyService"
android:process=":remote"
android:exported="true"/>
process 表示是一个远程服务
exported属性值为true,表示其它app可以引用这个服务。
到目前为止,服务端的工作已经完成了。
二.客户端编写
- 新建一个项目或新建一个module,名字为client
- 将服务端的aidl文件夹拷贝到client下,和java目录同级,编译
- 编写客户端布局和代码
- 布局就是两个edittext输入要计算的值,一个button点击时触发计算方法,一个TextView显示运算结果,此处就略去
- 代码如下:
public class MainActivity extends AppCompatActivity {
private EditText et_num1,et_num2;
private Button btn_add;
private TextView tv_result;
private IAddAidl iAddAidl;
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iAddAidl = IAddAidl.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
iAddAidl = null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initAction();
//绑定服务
bindService();
}
private void initView() {
et_num1 = (EditText) findViewById(R.id.et_num1);
et_num2 = (EditText) findViewById(R.id.et_num2);
btn_add = (Button) findViewById(R.id.btn_add);
tv_result = (TextView) findViewById(R.id.tv_result);
}
private void initAction() {
btn_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int num1 = Integer.parseInt(et_num1.getText().toString().trim());
int num2 = Integer.parseInt(et_num2.getText().toString().trim());
try {
int result =iAddAidl.add(num1,num2);
tv_result.setText(result+"");
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
private void bindService() {
Intent intent = new Intent();
//5.0之后需要显示启动,需要完整包名
intent.setComponent(new ComponentName("com.lyj.aidldemo","com.lyj.aidldemo.MyService"));
bindService(intent,conn, Context.BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
super.onDestroy();
//onDestory()中解绑
unbindService(conn);
}
}
首先,在onCreate()的时候绑定了服务,注意,5.0之后需要显示启动,需要完整的包名和服务类名
其次,在服务连接(onServiceConnect())时,获取IAddAidl对象,
最后,在点击的时候,iAddAidl调用其add方法,就可以计算出值了
3.运行
先运行服务端app,然后运行客户端app,在客户端的app中并未实现加到方法,却调用服务端的方法,实现了加的运算。