1/*
2 * Copyright 2016, 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
17package com.android.managedprovisioning.common;
18
19import static com.android.internal.util.Preconditions.checkNotNull;
20
21import android.annotation.NonNull;
22import android.annotation.Nullable;
23import android.content.Context;
24import android.content.pm.ApplicationInfo;
25import android.content.pm.PackageManager;
26import android.graphics.drawable.Drawable;
27
28import com.android.internal.annotations.Immutable;
29
30/**
31 * Information relating to the currently installed MDM package manager.
32 */
33@Immutable
34public final class MdmPackageInfo {
35    // ToDo: add toString and equals for better testability.
36
37    public final Drawable packageIcon;
38    public final String appLabel;
39
40    /**
41     * Default constructor.
42     */
43    public MdmPackageInfo(@NonNull Drawable packageIcon, @NonNull String appLabel) {
44        this.packageIcon = checkNotNull(packageIcon, "package icon must not be null");
45        this.appLabel = checkNotNull(appLabel, "app label must not be null");
46    }
47
48    /**
49     * Constructs an {@link MdmPackageInfo} object by reading the data from the package manager.
50     *
51     * @param context a {@link Context} object
52     * @param packageName the name of the mdm package
53     * @return an {@link MdMPackageInfo} object for the given package, or {@code null} if the
54     *         package does not exist on the device
55     */
56    @Nullable
57    public static MdmPackageInfo createFromPackageName(@NonNull Context context,
58            @Nullable String packageName) {
59        if (packageName != null) {
60            PackageManager pm = context.getPackageManager();
61            try {
62                ApplicationInfo ai = pm.getApplicationInfo(packageName, /* default flags */ 0);
63                return new MdmPackageInfo(pm.getApplicationIcon(packageName),
64                        pm.getApplicationLabel(ai).toString());
65            } catch (PackageManager.NameNotFoundException e) {
66                // Package does not exist, ignore. Should never happen.
67                ProvisionLogger.logw("Package not currently installed: " + packageName);
68            }
69        }
70        return null;
71    }
72}
73