// Android开发中,有时候需要判断App是否在前台运行。 代码实现如下:
private boolean isRunningForeground(Context context) { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); ComponentName cn = am.getRunningTasks(1).get(0).topActivity; String currentPackageName = cn.getPackageName(); if (currentPackageName != null && currentPackageName.equals(getPackageName())) { return true; } return false; }
//注意:AndroidManifest.xml中需增加< uses-permission android:name =“android.permission.GET_TASKS” />
protected static boolean isTopActivity(Activity activity) { String packageName = "xxxxx"; ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1); if (tasksInfo.size() > 0) { System.out.println("---------------包名-----------" + tasksInfo.get(0).topActivity.getPackageName()); // 应用程序位于堆栈的顶层 if (packageName.equals(tasksInfo.get(0).topActivity.getPackageName())) { return true; } } return false; }
//需要添加android.permission.GET_TASKS权限
时间: 2024-09-15 10:54:43