編寫 AVF 應用程序

AVF 相容的應用程式有兩個部分:在主機 Android 作業系統上運行的應用程式部分和在 pVM 內的 Microdroid 上運行的應用程式部分。

在 Android 上運行的應用程式部分實現使用者介面、非機密業務邏輯,並建立和管理 pVM 的生命週期。

在 pVM 內的 Microdroid 上執行的應用程式部分負責執行需要安全執行的任何任務。

為了啟動應用程式的 pVM 部分並與之通信,您的主機應用程式會建立一個 pVM 並在 pVM 內的庫中執行本機共用程式庫。該函式庫實作了一個活頁夾服務,應用程式的主機部分使用該服務與 pVM 內的應用程式部分進行通訊。圖 1 顯示了應用程式和 Binder 通訊通道的兩部分:

AVF 應用程式載入和通信

圖 1. AVF 應用程式載入和通信

設定設定檔

您的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(), "asssets/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 上提供 Binder 服務時收到通知。收到通知後,您將連接到活頁夾伺服器,然後使用自訂 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