我使用以下代码在我的应用程序中获取当前的前台应用程序包名称。我有一个运行 android 5 的用户,它总是返回 null (我有其他运行 android 5 的用户确认我的代码正在运行!)。用户安装我的应用程序,授予权限(我检查了它们,我的应用程序具有使用权限USAGE_STATS_SERVICE
,然后我调用getCurrentForegroundPackage
它并返回 null。应用程序在大约一分钟之前运行......它正在许多其他设备上运行......在哪里可能是问题吗?有什么想法吗?
代码 - 获取前台应用程序包
public static String getCurrentForegroundPackage(Context context)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
String foregroundPackage = getCurrentForegroundPackage(context, Constants.CHECK_INTERVAL_SECOND);
if (foregroundPackage == null)
foregroundPackage = getCurrentForegroundPackage(context, Constants.CHECK_INTERVAL_MINUTE);
if (foregroundPackage == null)
foregroundPackage = getCurrentForegroundPackage(context, Constants.CHECK_INTERVAL_HOUR);
return foregroundPackage;
}
else
{
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
return componentInfo.getPackageName();
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static String getCurrentForegroundPackage(Context context, long interval)
{
long to = System.currentTimeMillis();
long from = to - interval;
UsageStatsManager manager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
UsageEvents usageEvents = manager.queryEvents(from, to);
return getForeGroundPackage(usageEvents);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static String getForeGroundPackage(UsageEvents usageEvents)
{
String packageName = null;
long highestMoveToForegroundTimeStamp = 0;
while (usageEvents.hasNextEvent())
{
UsageEvents.Event event = new UsageEvents.Event();
usageEvents.getNextEvent(event);
if (event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND)
{
long timeStamp = event.getTimeStamp();
if (timeStamp > highestMoveToForegroundTimeStamp)
{
packageName = event.getPackageName();
highestMoveToForegroundTimeStamp = timeStamp;
}
}
}
return packageName;
}
代码 - 检查我的应用程序是否有权限
@TargetApi(Build.VERSION_CODES.KITKAT)
public static boolean hasUsageAccess()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
try
{
PackageManager packageManager = MainApp.get().getPackageManager();
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(MainApp.get().getPackageName(), 0);
AppOpsManager appOpsManager = (AppOpsManager) MainApp.get().getSystemService(Context.APP_OPS_SERVICE);
int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName);
return mode == AppOpsManager.MODE_ALLOWED;
}
catch (Exception e)
{
L.e(PermissionUtil.class, e);
}
return false;
}
return true;
}