4.2.3 发送对象
03-发送对象 — Comprehensive Rust
译文 · 基于 Comprehensive Rust
原文链接: https://google.github.io/comprehensive-rust/android/aidl/types/objects.html
4.2.3 发送对象
AIDL 对象既可以作为具体的 AIDL 类型发送,也可以作为类型擦除后的 IBinder 接口发送:
birthday_service/aidl/com/example/birthdayservice/IBirthdayInfoProvider.aidl:
1
2
3
4
5
6
| package com.example.birthdayservice;
interface IBirthdayInfoProvider {
String name();
int years();
}
|
birthday_service/aidl/com/example/birthdayservice/IBirthdayService.aidl:
1
2
3
4
5
6
7
8
9
| import com.example.birthdayservice.IBirthdayInfoProvider;
interface IBirthdayService {
/** 同样的事,但使用 binder 对象。 */
String wishWithProvider(IBirthdayInfoProvider provider);
/** 同样的事,但使用 `IBinder`。 */
String wishWithErasedProvider(IBinder provider);
}
|
birthday_service/src/client.rs:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
| // Copyright 2024 Google LLC
// SPDX-License-Identifier: Apache-2.0
/// 实现 `IBirthdayInfoProvider` 接口的 Rust 结构体。
struct InfoProvider {
name: String,
age: u8,
}
impl binder::Interface for InfoProvider {}
impl IBirthdayInfoProvider for InfoProvider {
fn name(&self) -> binder::Result<String> {
Ok(self.name.clone())
}
fn years(&self) -> binder::Result<i32> {
Ok(self.age as i32)
}
}
fn main() {
binder::ProcessState::start_thread_pool();
let service = connect().expect("Failed to connect to BirthdayService");
// 为 `IBirthdayInfoProvider` 接口创建一个 binder 对象。
let provider = BnBirthdayInfoProvider::new_binder(
InfoProvider { name: name.clone(), age: years as u8 },
BinderFeatures::default(),
);
// 将该 binder 对象发送给服务。
service.wishWithProvider(&provider)?;
// 执行相同操作,但将 provider 作为 `SpIBinder` 传入。
service.wishWithErasedProvider(&provider.as_binder())?;
}
|
- 注意
BnBirthdayInfoProvider 的用法。它与我们之前见过的 BnBirthdayService 作用相同。