---
title: "Aidl 练习"
author: "notebook"
date: "2012-11-15T17:17:32Z"
tags: []
categories: ["移动开发"]
slug: "aidl"
draft: false
lastmod: "2012-11-15T17:17:31Z"
id: 1726420
url: "https://notebook.iteye.com/blog/1726420"
---

什么是AIDL：Android Interface definition language，android内部进程通信接口的描述语言，通过它我们可以定义进程间的通信接口  
有什么用途：用于不同进程中数据的交换  
实现步骤：  
1.在com.aidl包下建立 IMyAidl.aidl

.aidl文件的内容与Java代码非常相似，但要注意，不能加修饰符（例如，public、private）、AIDL服务不支持的数据类型（例如，InputStream、OutputStream）等内容。

```
package com.aidl;
interface IMyAidl{
String getValue();
}
```

 2.编译后在gen下生成了对应的.java文件

3.编写一个service，好像aidl都要配合service来使用，里面实现了IMyAidl.Stub

```
public class MyService extends Service{
public class MyAidl extends IMyAidl.Stub{

	@Override
	public String getValue() throws RemoteException {
		// TODO Auto-generated method stub
		return "aidl test";
	}
	
}
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return new MyAidl();
	}

}
```

 配置service

```
 <service android:name=".MyService">
        <intent-filter >
        <action android:name="com.aidl.IMyAidl"/>
        </intent-filter>
        </service>
```

 4.在activity通过bindService([Intent]() service, [ServiceConnection]() conn, int flags)方法绑定服务，得到IMyAidl，调用getValue()，这样activity就可以得到从service传来的值了。

```
public class AIDLTestActivity extends Activity {
	private IMyAidl aidl;
	private TextView tx;
	 private  ServiceConnection conn = new ServiceConnection() {
			
			@Override
			public void onServiceDisconnected(ComponentName name) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				// 通过服务获得里面的定义的MyAidl类
				  aidl = IMyAidl.Stub.asInterface(service);
			}
		};
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tx = (TextView)findViewById(R.id.tx);
        Button bt1 = (Button)findViewById(R.id.bt1);
        Button bt2 = (Button)findViewById(R.id.bt2);
        bt1.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//绑定服务
				bindService(new Intent("com.aidl.IMyAidl"), conn, Context.BIND_AUTO_CREATE);
			}
		});
        bt2.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (aidl!=null) {
					try {
						//通过IMyAidl得到service传来的值
						tx.setText(aidl.getValue());
					} catch (RemoteException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
    }
}
```

 总结：  这里简单练习下，在静默安装和拦截电话都用到aidl，有空再写这些例子练习了。