我使用bellow代码在Android中获取应用程序名称。例如在Galaxy S4上;如果手机在Home screen
,则以下功能会返回TouchWiz home
。但是,在注4中,函数返回Google Home
。我们是否有任何方法可以维护应用程序名称或根据设备名称检测名称?目前,我将Home screen
保存在与设备名称对应的列表中。但是,我认为它不会涵盖所有可能的情况。
public String getAppName() {
String foregroundProcess = "";
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
// Sort the stats by the last time used
if (stats != null) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : stats) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
String topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
foregroundProcess = topPackageName;
}
}
} else {
@SuppressWarnings("deprecation")
ActivityManager.RunningTaskInfo foregroundTaskInfo = activityManager.getRunningTasks(1).get(0);
foregroundProcess = foregroundTaskInfo.topActivity.getPackageName();
}
//Convert package name to application name
final PackageManager pm = getApplicationContext().getPackageManager();
ApplicationInfo ai;
try {
ai = pm.getApplicationInfo(foregroundProcess, 0);
} catch (final PackageManager.NameNotFoundException e) {
ai = null;
}
String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
return applicationName;
}