相容於 AVF 的應用程式包含兩個部分:在主機 Android OS 上執行的應用程式部分,以及在 pVM 中執行的 Microdroid 應用程式部分。
在 Android 上執行的應用程式部分會實作使用者介面、非機密的商業邏輯,並建立及管理 pVM 的生命週期。
在 pVM 中執行 Microdroid 的應用程式部分,負責執行需要安全執行的任何工作。
如要啟動應用程式的 pVM 部分並與其通訊,主機應用程式會建立 pVM,並在 pVM 中執行原生共用程式庫。這個程式庫會實作 Binder 服務,讓應用程式主機部分可與 pVM 中的應用程式部分通訊。圖 1 顯示應用程式的兩個部分和 Binder 通訊管道:
設定設定檔
vm_config.json
檔案應包含 pVM 的作業系統和共用程式庫的項目。以下 assets/vm_config.json
檔案顯示 Microdroid 和共用原生程式庫的設定檔項目:
{
"os": {
"name": "microdroid"
},
"task": {
"type": "microdroid_launcher",
"command": MicrodroidTestNativeLib.so",
}
}
實作 Binder 服務
在共用程式庫中實作 Binder 服務。例如:
extern "C"
int android_native_main(int, char**) {
// Implement your binder service here
}
建立應用程式程式碼
在應用程式的主機部分中,建立可準備設定檔、載入 (或建立) VM 句柄,以及執行 VM 的程式碼。例如:
// Prepare the configuration file
VirtualMachineConfig config = new VirtualMachineConfig
.Builder(getApplication(), "assets/vm_config.json")
.build();
// Load (or create) the handle to a VM
VirtualMachine vm = VirtualMachineManager
.getInstance(getApplication())
.getOrCreate("my_vm", config);
// Run the VM
vm.run();
與應用程式的 VM 部分進行通訊
如要與應用程式的 VM 部分通訊,您必須先註冊回呼,以便在 VM 上的繫結器服務就緒時收到通知。收到通知後,您可以連線至繫結器伺服器,然後使用自訂 AIDL 介面與伺服器通訊。例如:
// Register the callback
vm.setCallback(Executors.newSingleThreadExecutor(),
new VirtualmachineCallback() {
@Override
public void onPayloadReady(VirtualMachine vm) {
// Connect to the binder server
IBinder binder = vm.connectToVsockServer(PORT).get();
IMyService svc = IMyService.Stub.asInterface(binder);
// Talk with server using custom AIDL interface
Result res = svc.doSomething();
}
}); //exception handling & proper threading omitted
vm.run();
如要下載示範應用程式的原始碼,以便展示本文中的步驟,請參閱 MicrodroidDemo。