Android开发笔记 ——(5)AIDL
chenhh
- 关注
Android开发笔记 ——(5)AIDL
AIDL全称:Android Interface definition language
作用:进程间的通信接口,相当于A进程(客户端)可以通过AIDL接口去调用另一个进程B(服务端)的方法
使用:
1、创建aidl文件
2、自动生成的java文件
3、使用aidl
AIDL和contentprovide的区别?
用途不一样, aidl调用服务的相关方法,强调的是方法。contentprovide强调的是数据之间的共享。
B进程这边:
创建aidl文件:
定义远程接口:
// IMyAidlInterface.aidl
package com.example.servicedemo;
// Declare any non-default types here with import statements
interface IMyAidlInterface {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
//定义自己所需要的方法:显示当前服务的进度
void showProgress();
}
//绑定
//IBinder:在android中用于远程操作对象的一个基本接口
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
Log.e("TAG","服务绑定了");
//Binder
return new IMyAidlInterface.Stub(){
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
}
@Override
public void showProgress() throws RemoteException {
Log.e("TAG","当前进度是" + i);
}
};
}
A进程这边复制B进程生成的AIDL代码,然后就可以使用B进程的AIDL接口中的方法了。
使用接口:
package com.example.aidldemo;
import android.content.ComponentName;
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.util.Log;
import android.view.View;
import com.example.servicedemo.IMyAidlInterface;
public class MainActivity extends AppCompatActivity {
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
IMyAidlInterface imai = IMyAidlInterface.Stub.asInterface(iBinder);
try {
imai.showProgress();
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void operate(View v){
switch(v.getId()){
case R.id.start:
//远程启动服务
Intent it = new Intent();
it.setAction("com.imooc.myservice");
it.setPackage("com.example.servicedemo");
startService(it);
break;
case R.id.stop:
Intent it2 = new Intent();
it2.setAction("com.imooc.myservice");
it2.setPackage("com.example.servicedemo");
stopService(it2);
break;
case R.id.bind:
Intent it3 = new Intent();
it3.setAction("com.imooc.myservice");
it3.setPackage("com.example.servicedemo");
bindService(it3,conn,BIND_AUTO_CREATE);
break;
case R.id.unbind:
unbindService(conn);
break;
}
}
}
本文为 chenhh 独立观点,未经授权禁止转载。
如需授权、对文章有疑问或需删除稿件,请联系 FreeBuf 客服小蜜蜂(微信:freebee1024)
如需授权、对文章有疑问或需删除稿件,请联系 FreeBuf 客服小蜜蜂(微信:freebee1024)
被以下专辑收录,发现更多精彩内容
+ 收入我的专辑
+ 加入我的收藏
相关推荐
Android开发笔记 ——(11)流行框架
2021-12-27
Android开发笔记 ——(10)高级控件
2021-12-27
Android开发笔记 ——(9)AsyncTask异步任务
2021-12-24