1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.system.virtualmachine;
18 
19 import static android.content.pm.PackageManager.FEATURE_VIRTUALIZATION_FRAMEWORK;
20 
21 import android.annotation.SystemApi;
22 import android.app.SystemServiceRegistry;
23 import android.content.Context;
24 
25 /**
26  * Holds initialization code for virtualization module
27  *
28  * @hide
29  */
30 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
31 public class VirtualizationFrameworkInitializer {
32 
VirtualizationFrameworkInitializer()33     private VirtualizationFrameworkInitializer() {}
34 
35     /**
36      * Called by the static initializer in the {@link SystemServiceRegistry}, and registers {@link
37      * VirtualMachineManager} to the {@link Context}. so that it's accessible from {@link
38      * Context#getSystemService(String)}.
39      */
registerServiceWrappers()40     public static void registerServiceWrappers() {
41         // Note: it's important that the getPackageManager().hasSystemFeature() check is executed
42         // in the lambda, and not directly in the registerServiceWrappers method. The
43         // registerServiceWrappers is called during Zygote static initialization, and at that
44         // point the PackageManager is not available yet.
45         //
46         // On the other hand, the lambda is executed after the app calls Context.getSystemService
47         // (VirtualMachineManager.class), at which point the PackageManager is available. The
48         // result of the lambda is cached on per-context basis.
49         SystemServiceRegistry.registerContextAwareService(
50                 Context.VIRTUALIZATION_SERVICE,
51                 VirtualMachineManager.class,
52                 ctx ->
53                         ctx.getPackageManager().hasSystemFeature(FEATURE_VIRTUALIZATION_FRAMEWORK)
54                                 ? new VirtualMachineManager(ctx)
55                                 : null);
56     }
57 }
58