Java Code Examples for android.provider.Settings#ACTION_USAGE_ACCESS_SETTINGS

The following examples show how to use android.provider.Settings#ACTION_USAGE_ACCESS_SETTINGS . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BackgroundUtil.java    From AndroidProcess with Apache License 2.0 6 votes vote down vote up
/**
 * 方法4:通过使用UsageStatsManager获取,此方法是ndroid5.0A之后提供的API
 * 必须:
 * 1. 此方法只在android5.0以上有效
 * 2. AndroidManifest中加入此权限<uses-permission xmlns:tools="http://schemas.android.com/tools" android:name="android.permission.PACKAGE_USAGE_STATS"
 * tools:ignore="ProtectedPermissions" />
 * 3. 打开手机设置,点击安全-高级,在有权查看使用情况的应用中,为这个App打上勾
 *
 * @param context     上下文参数
 * @param packageName 需要检查是否位于栈顶的App的包名
 * @return
 */

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static boolean queryUsageStats(Context context, String packageName) {
    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;
        }
    }
    RecentUseComparator mRecentComp = new RecentUseComparator();
    long ts = System.currentTimeMillis();
    UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService("usagestats");
    List<UsageStats> usageStats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, ts - 1000 * 10, ts);
    if (usageStats == null || usageStats.size() == 0) {
        if (HavaPermissionForTest(context) == false) {
            Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            Toast.makeText(context, "权限不够\n请打开手机设置,点击安全-高级,在有权查看使用情况的应用中,为这个App打上勾", Toast.LENGTH_SHORT).show();
        }
        return false;
    }
    Collections.sort(usageStats, mRecentComp);
    String currentTopPackage = usageStats.get(0).getPackageName();
    if (currentTopPackage.equals(packageName)) {
        return true;
    } else {
        return false;
    }
}
 
Example 2
Source File: AppUsagePlugin.java    From flutter-plugins with MIT License 5 votes vote down vote up
static void handlePermissions(Context context) {
    // If permission not enabled, open the settings screen
    if (Stats.permissionRequired(context)){
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        context.startActivity(intent);
    }
}
 
Example 3
Source File: ProcessManagerEngine.java    From MobileGuard with MIT License 5 votes vote down vote up
/**
 * request the get usage states permission.
 * @param context
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public static void requestUsageStatesPermission(Context context) {
    Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}
 
Example 4
Source File: MainActivity.java    From GrabQQPWD with Apache License 2.0 5 votes vote down vote up
private boolean checkUsagePermission() {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        AppOpsManager appOps = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
        int mode = 0;
        mode = appOps.checkOpNoThrow("android:get_usage_stats", android.os.Process.myUid(), getPackageName());
        boolean granted = mode == AppOpsManager.MODE_ALLOWED;
        if (!granted) {
            Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
            startActivityForResult(intent, 2);
            return false;
        }
    }
    return true;
}
 
Example 5
Source File: PermissionDialogActivity.java    From SoloPi with Apache License 2.0 4 votes vote down vote up
/**
 * 权限分组
 */
private void groupPermissions() {
    List<String> permissions = getIntent().getStringArrayListExtra(PERMISSIONS_KEY);
    Map<Integer, GroupPermission> currentPermissions = new LinkedHashMap<>();

    // 按照分组过一遍
    for (String permission : permissions) {
        int group;
        switch (permission) {
            case "float":
                group = PERMISSION_FLOAT;
                break;
            case "root":
                group = PERMISSION_ROOT;
                break;
            case "adb":
                group = PERMISSION_ADB;
                break;
            case Settings.ACTION_USAGE_ACCESS_SETTINGS:
                group = PERMISSION_USAGE;
                break;
            case Settings.ACTION_ACCESSIBILITY_SETTINGS:
                group = PERMISSION_ACCESSIBILITY;
                break;
            case "screenRecord":
                group = PERMISSION_RECORD;
                break;
            case "background":
                group = PERMISSION_BACKGROUND;
                break;
            default:
                if (permission.startsWith("Android=")) {
                    group = PERMISSION_ANDROID;
                } else if (permission.startsWith("toast:")) {
                    group = PERMISSION_TOAST;
                } else {
                    group = PERMISSION_DYNAMIC;
                }
                break;
        }

        // 如果有同分组
        GroupPermission permissionG = currentPermissions.get(group);
        if (permissionG == null) {
            permissionG = new GroupPermission(group);
            currentPermissions.put(group, permissionG);
        }

        permissionG.addPermission(permission);
    }

    // 设置下实际需要的权限
    allPermissions = new ArrayList<>(currentPermissions.values());
}
 
Example 6
Source File: MainPreferenceFragment.java    From kcanotify_h5-master with GNU General Public License v3.0 4 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void showObtainingUsageStatPermission() {
    Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
    startActivityForResult(intent, REQUEST_USAGESTAT_PERMISSION);
}
 
Example 7
Source File: AppUtils.java    From Common with Apache License 2.0 4 votes vote down vote up
private static String getForegroundProcessName(final Context context) {
    ActivityManager am =
            (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> pInfo = am.getRunningAppProcesses();
    if (pInfo != null && pInfo.size() > 0) {
        for (ActivityManager.RunningAppProcessInfo aInfo : pInfo) {
            if (aInfo.importance
                    == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return aInfo.processName;
            }
        }
    }
    if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP) {
        PackageManager pm = context.getPackageManager();
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        List<ResolveInfo> list =
                pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        Log.i("ProcessUtils", list.toString());
        if (list.size() <= 0) {
            Log.i("ProcessUtils", "getForegroundProcessName: noun of access to usage information.");
            return "";
        }
        try {
            // Access to usage information.
            ApplicationInfo info = pm.getApplicationInfo(context.getPackageName(), 0);
            AppOpsManager aom = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, info.uid,
                    info.packageName) != AppOpsManager.MODE_ALLOWED) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
            if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
                    info.uid,
                    info.packageName) != AppOpsManager.MODE_ALLOWED) {
                Log.i("ProcessUtils", "getForegroundProcessName: refuse to device usage stats.");
                return "";
            }
            UsageStatsManager usageStatsManager = (UsageStatsManager) context
                    .getSystemService(Context.USAGE_STATS_SERVICE);
            List<UsageStats> usageStatsList = null;
            if (usageStatsManager != null) {
                long endTime = System.currentTimeMillis();
                long beginTime = endTime - 86400000 * 7;
                usageStatsList = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST,
                        beginTime, endTime);
            }
            if (usageStatsList == null || usageStatsList.isEmpty()) return null;
            UsageStats recentStats = null;
            for (UsageStats usageStats : usageStatsList) {
                if (recentStats == null
                        || usageStats.getLastTimeUsed() > recentStats.getLastTimeUsed()) {
                    recentStats = usageStats;
                }
            }
            return recentStats == null ? null : recentStats.getPackageName();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }
    return "";
}
 
Example 8
Source File: DataManager.java    From AppsMonitor with MIT License 4 votes vote down vote up
public void requestPermission(Context context) {
    Intent intent = new Intent(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
    intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}
 
Example 9
Source File: ProcessUtils.java    From Android-UtilCode with Apache License 2.0 4 votes vote down vote up
/**
 * 获取前台线程包名
 * <p>当不是查看当前App,且SDK大于21时,
 * 需添加权限 {@code <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"/>}</p>
 *
 * @return 前台应用包名
 */
public static String getForegroundProcessName() {
    ActivityManager manager = (ActivityManager) Utils.getContext().getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> pInfo = manager.getRunningAppProcesses();
    if (pInfo != null && pInfo.size() != 0) {
        for (ActivityManager.RunningAppProcessInfo aInfo : pInfo) {
            if (aInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return aInfo.processName;
            }
        }
    }
    if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP) {
        PackageManager packageManager = Utils.getContext().getPackageManager();
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        System.out.println(list);
        if (list.size() > 0) {// 有"有权查看使用权限的应用"选项
            try {
                ApplicationInfo info = packageManager.getApplicationInfo(Utils.getContext().getPackageName(), 0);
                AppOpsManager aom = (AppOpsManager) Utils.getContext().getSystemService(Context.APP_OPS_SERVICE);
                if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, info.uid, info.packageName) != AppOpsManager.MODE_ALLOWED) {
                    Utils.getContext().startActivity(intent);
                }
                if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, info.uid, info.packageName) != AppOpsManager.MODE_ALLOWED) {
                    LogUtils.d("getForegroundApp", "没有打开\"有权查看使用权限的应用\"选项");
                    return null;
                }
                UsageStatsManager usageStatsManager = (UsageStatsManager) Utils.getContext().getSystemService(Context.USAGE_STATS_SERVICE);
                long endTime = System.currentTimeMillis();
                long beginTime = endTime - 86400000 * 7;
                List<UsageStats> usageStatses = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, beginTime, endTime);
                if (usageStatses == null || usageStatses.isEmpty()) return null;
                UsageStats recentStats = null;
                for (UsageStats usageStats : usageStatses) {
                    if (recentStats == null || usageStats.getLastTimeUsed() > recentStats.getLastTimeUsed()) {
                        recentStats = usageStats;
                    }
                }
                return recentStats == null ? null : recentStats.getPackageName();
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            LogUtils.d("getForegroundApp", "无\"有权查看使用权限的应用\"选项");
        }
    }
    return null;
}
 
Example 10
Source File: BaseActivity.java    From UseTimeStatistic with MIT License 4 votes vote down vote up
private void jumpToSystemPermissionActivity(){
    Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
    startActivity(intent);
}
 
Example 11
Source File: ActivityUsageStatsImpl.java    From MiPushFramework with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void guideToEnable(Context context) {
    Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}
 
Example 12
Source File: ProcessUtils.java    From AndroidUtilCode with Apache License 2.0 4 votes vote down vote up
/**
 * Return the foreground process name.
 * <p>Target APIs greater than 21 must hold
 * {@code <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />}</p>
 *
 * @return the foreground process name
 */
public static String getForegroundProcessName() {
    ActivityManager am =
            (ActivityManager) Utils.getApp().getSystemService(Context.ACTIVITY_SERVICE);
    //noinspection ConstantConditions
    List<ActivityManager.RunningAppProcessInfo> pInfo = am.getRunningAppProcesses();
    if (pInfo != null && pInfo.size() > 0) {
        for (ActivityManager.RunningAppProcessInfo aInfo : pInfo) {
            if (aInfo.importance
                    == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return aInfo.processName;
            }
        }
    }
    if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP) {
        PackageManager pm = Utils.getApp().getPackageManager();
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        List<ResolveInfo> list =
                pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        Log.i("ProcessUtils", list.toString());
        if (list.size() <= 0) {
            Log.i("ProcessUtils",
                    "getForegroundProcessName: noun of access to usage information.");
            return "";
        }
        try {// Access to usage information.
            ApplicationInfo info =
                    pm.getApplicationInfo(Utils.getApp().getPackageName(), 0);
            AppOpsManager aom =
                    (AppOpsManager) Utils.getApp().getSystemService(Context.APP_OPS_SERVICE);
            if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
                    info.uid,
                    info.packageName) != AppOpsManager.MODE_ALLOWED) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Utils.getApp().startActivity(intent);
            }
            if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
                    info.uid,
                    info.packageName) != AppOpsManager.MODE_ALLOWED) {
                Log.i("ProcessUtils",
                        "getForegroundProcessName: refuse to device usage stats.");
                return "";
            }
            UsageStatsManager usageStatsManager = (UsageStatsManager) Utils.getApp()
                    .getSystemService(Context.USAGE_STATS_SERVICE);
            List<UsageStats> usageStatsList = null;
            if (usageStatsManager != null) {
                long endTime = System.currentTimeMillis();
                long beginTime = endTime - 86400000 * 7;
                usageStatsList = usageStatsManager
                        .queryUsageStats(UsageStatsManager.INTERVAL_BEST,
                                beginTime, endTime);
            }
            if (usageStatsList == null || usageStatsList.isEmpty()) return "";
            UsageStats recentStats = null;
            for (UsageStats usageStats : usageStatsList) {
                if (recentStats == null
                        || usageStats.getLastTimeUsed() > recentStats.getLastTimeUsed()) {
                    recentStats = usageStats;
                }
            }
            return recentStats == null ? null : recentStats.getPackageName();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }
    return "";
}
 
Example 13
Source File: SettingsFragment.java    From always-on-amoled with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean onPreferenceChange(final Preference preference, Object o) {
    prefs.apply();
    Utils.logDebug("Preference change", preference.getKey() + " Value:" + o.toString());

    if (preference.getKey().equals("notifications_alerts")) {
        if ((boolean) o)
            return checkNotificationsPermission(context, true);
        return true;
    }
    if (preference.getKey().equals("raise_to_wake")) {
        if (!Utils.hasFingerprintSensor(context))
            askDeviceAdmin(R.string.settings_raise_to_wake_device_admin);
        restartService();
    }
    if (preference.getKey().equals("stop_delay"))
        if (!Utils.hasFingerprintSensor(context))
            askDeviceAdmin(R.string.settings_raise_to_wake_device_admin);
    if (preference.getKey().equals("persistent_notification") && !(boolean) o) {
        Snackbar.make(rootView, R.string.warning_1_harm_performance, 10000).setAction(R.string.action_revert, v -> {
            ((CheckBoxPreference) preference).setChecked(true);
            restartService();
        }).show();
        restartService();
    }
    if (preference.getKey().equals("enabled")) {
        context.sendBroadcast(new Intent(TOGGLED));
        restartService();
    }
    if (preference.getKey().equals("proximity_to_lock")) {
        if (Shell.SU.available() || (Utils.isAndroidNewerThanL() && !Build.MANUFACTURER.equalsIgnoreCase("samsung")))
            return true;
        else {
            DevicePolicyManager mDPM = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
            if ((mDPM != null && mDPM.isAdminActive(mAdminName))) {
                return true;
            }
            new AlertDialog.Builder(getActivity()).setTitle(getString(android.R.string.dialog_alert_title) + "!")
                    .setMessage(getString(R.string.warning_7_disable_fingerprint))
                    .setPositiveButton(getString(android.R.string.yes), (dialogInterface, i) -> {
                        askDeviceAdmin(R.string.settings_raise_to_wake_device_admin);
                    })
                    .setNegativeButton(getString(android.R.string.no), (dialogInterface, i) -> {
                        dialogInterface.dismiss();
                    })
                    .show();
            return false;
        }
    }
    if (preference.getKey().equals("startafterlock") && !(boolean) o)
        Snackbar.make(rootView, R.string.warning_4_device_not_secured, 10000).setAction(R.string.action_revert, v -> ((CheckBoxPreference) preference).setChecked(true)).show();
    if (preference.getKey().equals("doze_mode") && (boolean) o) {
        if (Shell.SU.available()) {
            if (!DozeManager.isDumpPermissionGranted(context))
                DozeManager.grantPermission(context, "android.permission.DUMP");
            if (!DozeManager.isDevicePowerPermissionGranted(context))
                DozeManager.grantPermission(context, "android.permission.DEVICE_POWER");
            return true;
        }
        Snackbar.make(rootView, R.string.warning_11_no_root, Snackbar.LENGTH_LONG).show();
        return false;
    }
    if (preference.getKey().equals("greenify_enabled") && (boolean) o) {
        if (!isPackageInstalled("com.oasisfeng.greenify")) {
            openPlayStoreUrl("com.oasisfeng.greenify", context);
            return false;
        }
    }
    if (preference.getKey().equals("camera_shortcut") || preference.getKey().equals("google_now_shortcut")) {
        try {
            if (!hasUsageAccess()) {
                Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
                PackageManager packageManager = getActivity().getPackageManager();
                if (intent.resolveActivity(packageManager) != null) {
                    startActivity(intent);
                } else {
                    Toast.makeText(context, "Please grant usage access permission manually for the app, your device can't do it automatically.", Toast.LENGTH_LONG).show();
                }
                return false;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }
    if (preference.getKey().equals("battery_saver"))
        if ((boolean) o) {
            ((TwoStatePreference) findPreference("doze_mode")).setChecked(true);
            setUpBatterySaverPermission();
        }
    return true;
}
 
Example 14
Source File: MainPreferenceFragment.java    From kcanotify with GNU General Public License v3.0 4 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void showObtainingUsageStatPermission() {
    Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
    startActivityForResult(intent, REQUEST_USAGESTAT_PERMISSION);
}
 
Example 15
Source File: PermissionUsageStats.java    From AcDisplay with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@NonNull
@Override
public Intent getIntentSettings() {
    return new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
}