写一个AIDL简示实例
时间: 2024-04-29 13:21:28 浏览: 28
好的,下面是一个简单的 AIDL 示例:
定义一个接口:
```aidl
// IService.aidl
interface IService {
int add(int a, int b);
}
```
实现接口:
```java
// ServiceImpl.java
public class ServiceImpl extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new IService.Stub() {
@Override
public int add(int a, int b) throws RemoteException {
return a + b;
}
};
}
}
```
在客户端中通过 `ServiceConnection` 连接服务并调用方法:
```java
// MainActivity.java
public class MainActivity extends AppCompatActivity {
private IService mService;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = IService.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, ServiceImpl.class);
bindService(intent, mConnection, BIND_AUTO_CREATE);
if (mService != null) {
try {
int result = mService.add(1, 2);
Log.d("MainActivity", "1 + 2 = " + result);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(mConnection);
}
}
```
注意事项:
1. AIDL 接口需要放在 `src/main/aidl` 目录下;
2. AIDL 接口中的方法必须声明抛出 `RemoteException` 异常;
3. 在客户端中必须使用 `IService.Stub.asInterface(service)` 方法将 `IBinder` 转换为 AIDL 接口;
4. 服务端与客户端需要使用相同的 AIDL 接口。
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)