AIDL

来源:互联网 发布:无线办公鼠标推荐知乎 编辑:程序博客网 时间:2024/06/03 08:32
1、什么是aidl:aidl是 Android Interface definition language的缩写,一看就明白,它是一种android进程间通信接口的描述语言,通过它我们可以定义进程间的通信接口

icp:interprocess communication :进程间通信

2、使用场景: 进程间通信,一个进程为其他多个进程提供服务。

实验项目包结构:

  服务器:客户端:    


A:服务器端(安卓项目):

一、定义接口(.aidl文件,自动编译成.java文件):

package com.yangxiaoru.test_aidl;
 interface  Minterface{
 int plus(in int a,in int b) ;
 }

2、暴露接口:

public class MyServer extends Service{




@Override
public IBinder onBind(Intent arg0) {
// 暴露接口
return new Minterface.Stub() {

@Override
public int plus(int a, int b) throws RemoteException {
return a+b;
}
};
}


}

3、在XML中申明

 <service android:name="com.yangxiaoru.test_aidl.MyServer" >
            <intent-filter>
                <action android:name="yangxiaoru" />
            </intent-filter>
        </service>

二、客户端:

1、在于服务器同名的包下,建立同名的.aidl文件

2、通过BindService使用服务:

public class MainActivity extends Activity {
private Minterface mInterface;
private ServiceConnection connection;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inite();
toBindService();
}


private void toBindService() {
Intent intent = new Intent("yangxiaoru");
bindService(intent, connection, Context.BIND_AUTO_CREATE);

}


private void inite() {
connection = new ServiceConnection() {


@Override
public void onServiceDisconnected(ComponentName arg0) {
mInterface = null;
}


@Override
public void onServiceConnected(ComponentName arg0, IBinder binder) {
mInterface = Minterface.Stub.asInterface(binder);
try {
int x = mInterface.plus(2, 6);
System.out.println("2+6==" + x);
} catch (RemoteException e) {
System.out.println("远程调用出错");
}
}
};
}


}

注:bindService是一个异步方法。



0 0
原创粉丝点击