您的位置:首页 > 大数据 > 人工智能

AIDL

2016-04-11 13:45 591 查看
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是一个异步方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: