คิวข้อความด่วนด้วย AIDL

สำหรับ Android 12 คุณสามารถใช้คิวข้อความด่วนได้ ที่ใช้กับอินเทอร์เฟซ AIDL ที่ใช้แบ็กเอนด์ NDK ซึ่งช่วยให้กระบวนการสื่อสารกันได้โดยไม่เกิดค่าใช้จ่ายเพิ่มเติมและข้อจํากัดของธุรกรรม Binder หลังจากการตั้งค่าสั้นๆ การใช้ Stable AIDL ช่วยให้สื่อสารระหว่างระบบกับ กระบวนการของผู้ให้บริการ

ประเภทเพย์โหลดที่รองรับ

ข้อความที่ส่งระหว่างกระบวนการในคิวข้อความหน่วยความจำที่ใช้ร่วมกันต้องมีเลย์เอาต์หน่วยความจำเดียวกันในขอบเขตกระบวนการและไม่มีพอยน์เตอร์ กำลังพยายามสร้าง AidlMessageQueue ที่มีประเภทที่ไม่รองรับจะทำให้เกิดข้อผิดพลาดในการคอมไพล์

ประเภทคิวที่รองรับ

ประเภทคิวเดียวกันจาก HIDL บ่อยครั้ง ซึ่งเรียกว่า "รสชาติ" ได้รับการรองรับด้วย AIDL ค่าเหล่านี้จะใช้เป็นอาร์กิวเมนต์เทมเพลตสำหรับ คิวและข้อบ่งชี้

ประเภท HIDL ประเภท AIDL
android::hardware::kSynchronizedReadWrite android.hardware.common.fmq.SynchronizedReadWrite
android::hardware::kUnsynchronizedWrite android.hardware.common.fmq.UnsynchronizedWrite

วิธีใช้

กำหนดอินเทอร์เฟซ AIDL ที่จะส่ง MQDescriptor ไปยังกระบวนการอื่น MQDescriptor สามารถใช้ได้ทุกที่ที่ Parcelable ใช้ได้

อาร์กิวเมนต์เทมเพลตที่จำเป็นสำหรับ MQDescriptor คือประเภทเพย์โหลดและรสชาติของคิว

import android.hardware.common.fmq.MQDescriptor
import android.hardware.common.fmq.SynchronizedReadWrite

void getQueue(out MQDescriptor<int, SynchronizedReadWrite> mqDesc);

กระบวนการตั้งค่าแต่ละด้านของคิวข้อความเกือบจะเหมือนกับกระบวนการที่ใช้ HIDL เพียงแต่ใช้ประเภท AIDL

#include <fmq/AidlMessageQueue.h>
...
using ::android::AidlMessageQueue;
using ::aidl::android::hardware::common::fmq::MQDescriptor;
using ::aidl::android::hardware::common::fmq::SynchronizedReadWrite;
...
ndk::ScopedAStatus MyInterface::getQueue(MQDescriptor<int32_t, SynchronizedReadWrite>* mqDesc) {
    *mqDesc = mFmqSynchronized->dupeDesc();
    return ndk::ScopedAStatus::ok();
}
...
// Create the first side of the queue before servicing getQueue() in this example
mFmqSynchronized =
  new AidlMessageQueue<int32_t, SynchronizedReadWrite>(kNumElementsInQueue);

กระบวนการรับจะสร้างคิวอีกด้านด้วยข้อบ่งชี้ที่ได้รับจากอินเทอร์เฟซ AIDL

MQDescriptor<int32_t, SynchronizedReadWrite> desc;
auto ret = service->getQueue(true, &desc);
if (!ret.isOk()) {
   ...
}
// By default the constructor will reset the read and write pointers of the queue.
// Add a second `false` argument to avoid resetting the pointers.
mQueue = new (std::nothrow) AidlMessageQueue<int32_t, SynchronizedReadWrite>(desc);
if (!mQueue->isValid()) {
   ...
}

การใช้ AidlMessageQueue หลังจากการตั้งค่าจะเหมือนกับ HIDL MessageQueue API ทั้งหมดตามที่อธิบายไว้ในการใช้ MessageQueue ได้รับการสนับสนุนโดยสมบูรณ์ด้วย AidlMessageQueue โดยมีข้อยกเว้น 1 ข้อ ได้แก่

const MQDescriptor<T, flavor>* getDesc() แทนที่ด้วย MQDescriptor<T, U> dupeDesc() ซึ่งแสดงผล AIDL MQDescriptor