编写 AVF 应用

与 AVF 兼容的应用包含两个部分:在主机 Android OS 上运行的应用部分,以及在 pVM 内的 Microdroid 上运行的应用部分。

在 Android 上运行的应用部分会实现界面、非机密业务逻辑,并创建和管理 pVM 的生命周期。

在 pVM 内的 Microdroid 上运行的应用部分负责执行任何需要安全执行的任务。

为了启动应用的 pVM 部分并与其通信,您的主机应用会创建一个 pVM,并在该 pVM 内运行原生共享库。此库实现 Binder 服务,应用的主机部分使用该服务与应用在 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"  } } 

实现 Binder 服务

在共享库中,实现 Binder 服务。例如:

extern "C" int android_native_main(int, char**) { // Implement your binder service here } 

创建应用代码

在应用的主机部分,创建用于准备配置文件、向虚拟机加载(或创建)句柄以及运行虚拟机的代码。例如:

// 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(); 

与应用的虚拟机部分通信

如需与应用的虚拟机部分通信,请先注册一个回调,以便在虚拟机上的 Binder 服务准备就绪时收到通知。收到通知后,您将连接到 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