1 /* 2 * Copyright (C) 2021 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 com.android.helpers; 18 19 import static com.android.helpers.MetricUtility.constructKey; 20 21 import android.content.Context; 22 import android.content.pm.PackageInfo; 23 import android.content.pm.PackageManager; 24 import android.util.Log; 25 26 import androidx.test.core.app.ApplicationProvider; 27 28 import java.util.HashMap; 29 import java.util.List; 30 import java.util.Map; 31 32 /** 33 * This is a collector helper to use PackageManager to get app package versions. 34 */ 35 public class AppVersionHelper implements ICollectorHelper<Long> { 36 37 private static final String TAG = AppVersionHelper.class.getSimpleName(); 38 private static final String METRIC_PREFIX = "app-version-code-long"; 39 40 private Context context; 41 private PackageManager packageManager; 42 43 private String[] mPackageNames = {}; 44 setUp(String... packageNames)45 public void setUp(String... packageNames) { 46 context = ApplicationProvider.getApplicationContext().getApplicationContext(); 47 packageManager = context.getPackageManager(); 48 mPackageNames = packageNames; 49 } 50 51 @Override startCollecting()52 public boolean startCollecting() { 53 return true; 54 } 55 56 @Override getMetrics()57 public Map<String, Long> getMetrics() { 58 Map<String, Long> metrics = new HashMap<>(); 59 if (mPackageNames == null || mPackageNames.length == 0 || mPackageNames[0].length() == 0) { 60 // If no package specified, collects all. 61 // Additional option flags is set to 0, which is simply default. 62 List<PackageInfo> pkgInfos = packageManager.getInstalledPackages(0); 63 for (PackageInfo pkgInfo : pkgInfos) { 64 metrics.put(constructKey(METRIC_PREFIX, pkgInfo.packageName), 65 pkgInfo.getLongVersionCode()); 66 } 67 } else { 68 for (String pkg : mPackageNames) { 69 try { 70 // Additional option flags is set to 0, which is simply default. 71 PackageInfo pkgInfo = packageManager.getPackageInfo(pkg, 0); 72 metrics.put(constructKey(METRIC_PREFIX, pkg), 73 pkgInfo.getLongVersionCode()); 74 Log.d(TAG, "Found app version for package name " + pkg); 75 } catch (PackageManager.NameNotFoundException exception) { 76 Log.e(TAG, "Can't find package name " + pkg); 77 continue; 78 } 79 } 80 } 81 return metrics; 82 } 83 84 @Override stopCollecting()85 public boolean stopCollecting() { 86 return true; 87 } 88 } 89