android 11 aidl waitforservice使用示例
时间: 2024-11-09 12:21:56 浏览: 55
Android 11引入了AIDL(Android Interface Definition Language)的改进,包括`waitForService()`方法,它允许服务请求者阻塞直到服务可用。下面是一个简单的AIDL服务接口和客户端使用的示例:
首先,在服务端(`MyService.aidl`):
```aidl
interface MyService {
// 定义一个异步操作
void doSomething(String data, String replyTo);
}
```
然后,生成服务接口的Java文件(如`MyService.java`),并在`onCreate()`方法中开启服务:
```java
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return new Binder() {
@Override
public boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
switch (code) {
case DO_SOMETHING_TRANSACTION:
if (data != null && data.readString().equals(replyTo)) {
// 执行doSomething,并返回结果到reply
String result = "Service result for " + data.readString();
reply.writeString(result);
}
return true;
default:
return super.onTransact(code, data, reply, flags);
}
}
};
}
private static final String ACTION_DO_SOMETHING = "com.example.DO_SOMETHING";
private static final String.EXTRA_REPLY_TO = "reply_to";
@Nullable
@Override
public Intent getService(String name) {
if (name.equals(ACTION_DO_SOMETHING)) {
Intent serviceIntent = new Intent(this, MyService.class);
serviceIntent.putExtra(EXTRA_REPLY_TO, "service_wait_response");
startService(serviceIntent);
return serviceIntent;
}
return null;
}
}
// 启动服务时等待服务可用
Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent).waitforservice();
```
在客户端(例如`MainActivity.java`),你可以这样调用服务并等待:
```java
private boolean callAndAwaitResponse(MyService.Stub stub) {
Intent request = new Intent(ACTION_DO_SOMETHING);
request.putExtra(MyService.EXTRA_REPLY_TO, "client_wait_response");
try {
stub.doSomething(request, Looper.getMainLooper()); // 使用当前线程的消息队列作为回调
// 等待服务响应,如果超时或服务未启动,则会抛出异常
stub.waitForService();
} catch (RemoteException e) {
Log.e("MainActivity", "Error while calling service", e);
return false;
}
return true; // 如果到达这里,说明服务已响应
}
```
阅读全文