如何在Android中获取类的包/应用程序名称?

时间:2016-09-24 07:26:30

标签: android android-intent android-activity

我使用UsageStatsManager来获取应用程序名称,它运行良好。但是,我想了解一个应用程序的更多细节。例如,我的应用程序有三个活动,我希望在使用波纹管功能进行活动时获取活动的名称。但是,我尝试重命名活动名称,但是波纹管功能仍然返回应用程序包和应用程序名称。我该如何解决?

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;
    }
    final String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
    Log.d("Runing package",foregroundProcess);
    Log.d("Runing app",applicationName);
    return applicationName;
}

我尝试在 Manifest 文件中为该类指定名称,但它仍然是返回应用程序名称

   <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="Hello">
    <activity
        android:name="com.example.camera.AndroidCamera"
        android:label="AndroidCamera"
        android:screenOrientation="landscape">
    </activity>

提前致谢。

0 个答案:

没有答案
相关问题