與 AVF 相容的應用程式包含兩部分:在主機 Android 作業系統上執行的部分,以及在 pVM 內 Microdroid 上執行的部分。
在 Android 上執行的應用程式部分會實作使用者介面、非機密商業邏輯,並建立及管理 pVM 的生命週期。
在 pVM 內 Microdroid 上執行的應用程式部分,負責執行任何需要安全執行的工作。
如要啟動應用程式的 pVM 部分並與之通訊,主機應用程式會建立 pVM,並在 pVM 中執行原生共用程式庫。這個程式庫會實作繫結器服務,應用程式的主機部分會使用這項服務,與 pVM 內的應用程式部分通訊。圖 1 顯示應用程式的兩個部分和繫結器通訊管道:
調整設定檔
您的 vm_config.json
檔案應包含 pVM 的作業系統和共用程式庫項目。以下 assets/vm_config.json
檔案顯示 Microdroid 和共用原生程式庫的設定檔項目:
{
"os": {
"name": "microdroid"
},
"task": {
"type": "microdroid_launcher",
"command": "MicrodroidTestNativeLib.so"
}
}
實作繫結器服務
在共用程式庫中,實作繫結器服務。例如:
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。