AIDL サーバー
最後に、サービスを公開するサーバーを作成できます。
birthday_service/src/server.rs:
// Copyright 2024 Google LLC
// SPDX-License-Identifier: Apache-2.0
//! Birthday service.
use birthdayservice::BirthdayService;
use com_example_birthdayservice::aidl::com::example::birthdayservice::IBirthdayService::BnBirthdayService;
use com_example_birthdayservice::binder;
const SERVICE_IDENTIFIER: &str = "birthdayservice";
/// Entry point for birthday service.
fn main() {
let birthday_service = BirthdayService;
let birthday_service_binder = BnBirthdayService::new_binder(
birthday_service,
binder::BinderFeatures::default(),
);
binder::add_service(SERVICE_IDENTIFIER, birthday_service_binder.as_binder())
.expect("Failed to register service");
binder::ProcessState::join_thread_pool();
}
birthday_service/Android.bp:
rust_binary {
name: "birthday_server",
crate_name: "birthday_server",
srcs: ["src/server.rs"],
rustlibs: [
"com.example.birthdayservice-rust",
"libbirthdayservice",
],
prefer_rlib: true, // To avoid dynamic link error.
}
ユーザー定義のサービス実装(この場合は IBirthdayService を実装する BirthdayService 型)を受け取り、それを Binder サービスとして起動する プロセスには複数の手順があります。これは、C++ や他の言語から Binder を 使ったことがある受講者にとっては、慣れているものより複雑に見えるかもしれません。 各手順がなぜ必要なのかを受講者に説明してください。
- サービス型(
BirthdayService)のインスタンスを作成します。 - サービスオブジェクトを、対応する
Bn*型(この場合はBnBirthdayService) でラップします。この型は Binder によって生成され、C++ のBnBinder基底クラスに似た共通の Binder 機能を提供します。Rust には継承がないため、 生成されたBnBinderServiceの中にBirthdayServiceを入れるという コンポジションを使います。 add_serviceを呼び出し、サービス識別子とサービスオブジェクト (この例ではBnBirthdayServiceオブジェクト)を渡します。join_thread_poolを呼び出して現在のスレッドを Binder のスレッドプールに追加し、 接続の待機を開始します。