给一个android aidl的源码
时间: 2023-12-02 12:59:08 浏览: 73
安卓aidl学习源码
下面是一个简单的 Android AIDL 示例源代码:
定义一个 AIDL 接口:
```
// IMyAidlInterface.aidl
package com.example.aidl;
interface IMyAidlInterface {
int add(int a, int b);
}
```
实现这个接口:
```
// MyAidlInterfaceImpl.java
package com.example.aidl;
import android.os.RemoteException;
public class MyAidlInterfaceImpl extends IMyAidlInterface.Stub {
@Override
public int add(int a, int b) throws RemoteException {
return a + b;
}
}
```
在 manifest 文件中声明服务:
```
<service
android:name=".MyAidlInterfaceService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.example.aidl.IMyAidlInterface" />
</intent-filter>
</service>
```
创建服务类:
```
// MyAidlInterfaceService.java
package com.example.aidl;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
public class MyAidlInterfaceService extends Service {
private MyAidlInterfaceImpl myAidlInterfaceImpl;
public MyAidlInterfaceService() {
}
@Override
public IBinder onBind(Intent intent) {
if (myAidlInterfaceImpl == null) {
myAidlInterfaceImpl = new MyAidlInterfaceImpl();
}
return myAidlInterfaceImpl;
}
}
```
现在,你就可以在你的应用程序中使用这个 AIDL 接口了:
```
// MainActivity.java
package com.example.aidl;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private IMyAidlInterface myAidlInterface;
private boolean isBound;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setAction("com.example.aidl.IMyAidlInterface");
intent.setPackage("com.example.aidl");
isBound = bindService(intent, serviceConnection, BIND_AUTO_CREATE);
}
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
myAidlInterface = IMyAidlInterface.Stub.asInterface(iBinder);
try {
int result = myAidlInterface.add(1, 2);
Log.d("MainActivity", "Result: " + result);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
myAidlInterface = null;
}
};
@Override
protected void onDestroy() {
super.onDestroy();
if (isBound) {
unbindService(serviceConnection);
}
}
}
```
阅读全文