是否有getRunningTask API替代getRunningTask、API

2023-09-12 22:51:38 作者:Outsider

我是用getRunningTask API在我的应用程序之一,找到前台应用程序。这个API一直以来棒棒糖pcated德$ P $。在此之后去precation,我preferred getRunningAppProcess API以及Importance_Foreground。我也排除了REASON_SERVICE和REASON_PROVIDER从这个名单。我过滤掉了系统的应用基于一个逻辑,它完美地工作。问题是,如果应用程序A在前台,我得到的应用程序B作为尖峰。所以,这种方法是目前值得怀疑。是否有任何其他的替代getRunningTask API?还是我失去了在目前的做法任何简单的事情。请帮家伙。

I was using getRunningTask API in one of my application to find the Foreground application. This API has been deprecated since Lollipop. After this deprecation, I preferred getRunningAppProcess API along with Importance_Foreground. I also ruled out REASON_SERVICE and REASON_PROVIDER from this list. I filtered out the system applications based on a logic, which worked perfectly. The problem is that, If Application A is on foreground, I get Application B as a spike. So, this approach is currently questionable. Is there any other alternative to the getRunningTask API?? Or am I missing any simple thing in the current approach. Please help guys.

推荐答案

根据答案的这个问题

String getTopPackage(){
    long ts = System.currentTimeMillis();
    UsageStatsManager mUsageStatsManager = (UsageStatsManager)getSystemService("usagestats");
    List<UsageStats> usageStats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, ts-1000, ts);
    if (usageStats == null || usageStats.size() == 0) {
        return NONE_PKG;
    }
    Collections.sort(usageStats, mRecentComp);
    return usageStats.get(0).getPackageName();
}

这是 mRecentComp

static class RecentUseComparator implements Comparator<UsageStats> {

    @Override
    public int compare(UsageStats lhs, UsageStats rhs) {
        return (lhs.getLastTimeUsed() > rhs.getLastTimeUsed()) ? -1 : (lhs.getLastTimeUsed() == rhs.getLastTimeUsed()) ? 0 : 1;
    }
}

此权限是必要的:

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

和您将需要用户授权请求统计,使用此用户引导到设置页面:

And you will need user authorization to request the stats, use this to direct the user to the settings page:

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

你可以检查您是否已经有这样的权限:

And you can check if you already have permission like this:

public static boolean needPermissionForBlocking(Context context) {
    try {
        PackageManager packageManager = context.getPackageManager();
        ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
        AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName);
        return  (mode != AppOpsManager.MODE_ALLOWED);
    } catch (PackageManager.NameNotFoundException e) {
        return true;
    }
}