如何`getTopActivity`名称或获取当前在棒棒糖中运行的应用程序包名称?

时间:2015-01-21 11:35:07

标签: android android-5.0-lollipop

我正在创建一个应用锁定应用。如何在棒棒糖中获得当前的运行任务?在lollipop API中不推荐getRunningTaskinfo方法,那么如何克服这个问题?

8 个答案:

答案 0 :(得分:37)

试试这个:

ActivityManager mActivityManager =(ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);

if(Build.VERSION.SDK_INT > 20){
String mPackageName = mActivityManager.getRunningAppProcesses().get(0).processName;
}
else{
  String mpackageName = mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}

我们可以使用UsageStats:

public static String getTopAppName(Context context) {
    ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    String strName = "";
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            strName = getLollipopFGAppPackageName(context);
        } else {
            strName = mActivityManager.getRunningTasks(1).get(0).topActivity.getClassName();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return strName;
}


private static String getLollipopFGAppPackageName(Context ctx) {

    try {
        UsageStatsManager usageStatsManager = (UsageStatsManager) ctx.getSystemService("usagestats");
        long milliSecs = 60 * 1000;
        Date date = new Date();
        List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, date.getTime() - milliSecs, date.getTime());
        if (queryUsageStats.size() > 0) {
            Log.i("LPU", "queryUsageStats size: " + queryUsageStats.size());
        }
        long recentTime = 0;
        String recentPkg = "";
        for (int i = 0; i < queryUsageStats.size(); i++) {
            UsageStats stats = queryUsageStats.get(i);
            if (i == 0 && !"org.pervacio.pvadiag".equals(stats.getPackageName())) {
                Log.i("LPU", "PackageName: " + stats.getPackageName() + " " + stats.getLastTimeStamp());
            }
            if (stats.getLastTimeStamp() > recentTime) {
                recentTime = stats.getLastTimeStamp();
                recentPkg = stats.getPackageName();
            }
        }
        return recentPkg;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

//启用USAGE_STATS

    // Declare USAGE_STATS permisssion in manifest

    <uses-permission
    android:name="android.permission.PACKAGE_USAGE_STATS"
    tools:ignore="ProtectedPermissions" />


    Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
    startActivity(intent);

答案 1 :(得分:7)

在API 21或更高版本中获取正在运行的应用程序的最佳解决方案是尝试它。 这项工作对我来说

private String retriveNewApp() {
    if (VERSION.SDK_INT >= 21) {
        String currentApp = null;
        UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
        long time = System.currentTimeMillis();
        List<UsageStats> applist = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
        if (applist != null && applist.size() > 0) {
            SortedMap<Long, UsageStats> mySortedMap = new TreeMap<>();
            for (UsageStats usageStats : applist) {
                mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
            }
            if (mySortedMap != null && !mySortedMap.isEmpty()) {
                currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
            }
        }
        Log.e(TAG, "Current App in foreground is: " + currentApp);

        return currentApp;

    }
    else {

        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        String mm=(manager.getRunningTasks(1).get(0)).topActivity.getPackageName();
        Log.e(TAG, "Current App in foreground is: " + mm);
        return mm;
    }
}

答案 2 :(得分:5)

你确定吗?正如我根据最新的Android文档所看到的,LOLLIPOP更新不允许您了解有关除您自己以外的其他应用程序的任何信息!?

http://developer.android.com/reference/android/app/ActivityManager.html 您可以看到所有这些方法都已弃用!

答案 3 :(得分:4)

根据this;以下代码非常适合我:

MOVE_TO_FOREGROUNDMOVE_TO_BACKGROUND 在 sdk 21 中添加并在 sdk 29

中弃用

ACTIVITY_RESUMEDACTIVITY_PAUSED 添加到 sdk 29

public static String getTopPkgName(Context context) {
    String pkgName = null;

    UsageStatsManager usageStatsManager = (UsageStatsManager) context
            .getSystemService(Context.USAGE_STATS_SERVICE);

    final long timeTnterval= 1000 * 600;
    final long endTime = System.currentTimeMillis();
    final long beginTime = endTime - timeTnterval;
    final UsageEvents myUsageEvents = usageStatsManager .queryEvents(beginTime , endTime );
    while (myUsageEvents .hasNextEvent()) {
        UsageEvents.Event myEvent = new UsageEvents.Event();
        myUsageEvents .getNextEvent(myEvent );
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            switch (myEvent .getEventType()) {
                case UsageEvents.Event.ACTIVITY_RESUMED:
                    pkgName = myEvent .getPackageName();
                    break;
                case UsageEvents.Event.ACTIVITY_PAUSED:
                    if (myEvent .getPackageName().equals(pkgName )) {
                        pkgName = null;
                    }
            }
        }else {
            switch (event.getEventType()) {
                case UsageEvents.Event.MOVE_TO_FOREGROUND:
                    pkgName = myEvent .getPackageName();
                    break;
                case UsageEvents.Event.MOVE_TO_BACKGROUND:
                    if (myEvent .getPackageName().equals(pkgName )) {
                        pkgName = null;
                    }
            }
        }
    }

    return pkgName ;
}

答案 4 :(得分:3)

您可以使用AccessibilityService获取当前正在运行的应用。 辅助功能服务提供onAccessibilityEvent事件。

以下是一些示例代码。

@Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            if (event.getPackageName() != null && event.getClassName() != null) {
                Log.d("Foreground App", event.getPackageName().toString());  

            }
        }
    }

您可以找到有关辅助功能服务here

的更多信息

答案 5 :(得分:2)

试试这个..这对我有用。

ActivityManager activityManager = (ActivityManager) getSystemService (Context.ACTIVITY_SERVICE);

if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP)    
{

String packageName = activityManager.getRunningAppProcesses().get(0).processName;
} 
else if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP)
{
String packageName =  ProcessManager.getRunningForegroundApps(getApplicationContext()).get(0).getPackageName();

}
else
{
String packageName = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}

答案 6 :(得分:1)

@Manish Godhani的答案(https://stackoverflow.com/a/38829083/8179249)非常有效,但你必须为此提供正确的权限!

请参阅该答案的两个第一点:https://stackoverflow.com/a/42560422/8179249

它适用于我(在添加权限之前我也得到'null'),如下所示: Results given by the code of that answer, after adding permissions

答案 7 :(得分:0)

可以这样实现......

ActivityManager am =(ActivityManager)context.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
ActivityManager.RunningTaskInfo task = tasks.get(0); // current task
ComponentName rootActivity = task.baseActivity;


rootActivity.getPackageName();//*currently active applications package name*

对于棒棒糖:

ActivityManager mActivityManager =(ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);

if(Build.VERSION.SDK_INT > 20){
    String activityName =mActivityManager.getRunningAppProcesses().get(0).processName;
 }
else{
 String activityName =   mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}

完整示例check this out...