blob: af7ff41f44553533cbecd627a7694c07feb2b9e2 [file] [log] [blame]
Alan Viveretteb6a25732017-11-21 14:49:24 -05001/*
2 * Copyright (C) 2017 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.server.utils;
18
19import android.content.Context;
20import android.content.Intent;
21import android.content.pm.ResolveInfo;
22import android.util.Log;
23
24public class AppInstallerUtil {
25 private static final String LOG_TAG = "AppInstallerUtil";
26
27 private static Intent resolveIntent(Context context, Intent i) {
28 ResolveInfo result = context.getPackageManager().resolveActivity(i, 0);
29 return result != null ? new Intent(i.getAction())
30 .setClassName(result.activityInfo.packageName, result.activityInfo.name) : null;
31 }
32
33 /**
34 * Returns the package name of the app which installed a given packageName, if available.
35 */
36 public static String getInstallerPackageName(Context context, String packageName) {
37 String installerPackageName = null;
38 try {
39 installerPackageName =
40 context.getPackageManager().getInstallerPackageName(packageName);
41 } catch (IllegalArgumentException e) {
42 Log.e(LOG_TAG, "Exception while retrieving the package installer of " + packageName, e);
43 }
44 if (installerPackageName == null) {
45 return null;
46 }
47 return installerPackageName;
48 }
49
50 /**
51 * Returns an intent to launcher the installer for a given package name.
52 */
53 public static Intent createIntent(Context context, String installerPackageName,
54 String packageName) {
55 Intent intent = new Intent(Intent.ACTION_SHOW_APP_INFO).setPackage(installerPackageName);
56 final Intent result = resolveIntent(context, intent);
57 if (result != null) {
58 result.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName);
59 return result;
60 }
61 return null;
62 }
63
64 /**
65 * Convenience method that looks up the installerPackageName.
66 */
67 public static Intent createIntent(Context context, String packageName) {
68 String installerPackageName = getInstallerPackageName(context, packageName);
69 return createIntent(context, installerPackageName, packageName);
70 }
71}