Search in sources :

Example 21 with AppOpsManager

use of android.app.AppOpsManager in project android_packages_apps_Settings by LineageOS.

the class AppOpsState method buildState.

public List<AppOpEntry> buildState(OpsTemplate tpl, int uid, String packageName, Comparator<AppOpEntry> comparator, boolean privacyGuard) {
    final Context context = mContext;
    final HashMap<String, AppEntry> appEntries = new HashMap<String, AppEntry>();
    final List<AppOpEntry> entries = new ArrayList<AppOpEntry>();
    final ArrayList<String> perms = new ArrayList<String>();
    final ArrayList<Integer> permOps = new ArrayList<Integer>();
    final int[] opToOrder = new int[AppOpsManager._NUM_OP];
    final Set<Integer> privacyGuardOps = new HashSet<>();
    for (int i = 0; i < tpl.ops.length; i++) {
        if (privacyGuard && isPrivacyGuardOp(tpl.ops[i])) {
            // If there's a permission for this Privacy Guard OP, then
            // we don't have to treat it in a special way. The application
            // should have the permission declared if it uses it, so we
            // will add this later when we query PackageManager
            String perm = AppOpsManager.opToPermission(tpl.ops[i]);
            if (perm != null) {
                if (DEBUG)
                    Log.d(TAG, "Adding " + AppOpsManager.opToName(tpl.ops[i]) + " (" + tpl.ops[i] + ") to privacyGuardOps");
                privacyGuardOps.add(tpl.ops[i]);
            } else {
                if (DEBUG)
                    Log.d(TAG, "Not adding " + AppOpsManager.opToName(tpl.ops[i]) + " (" + tpl.ops[i] + ") with perm " + perm + " to privacyGuardOps");
            }
        }
        if (tpl.showPerms[i]) {
            String perm = AppOpsManager.opToPermission(tpl.ops[i]);
            if (perm != null && !perms.contains(perm)) {
                perms.add(perm);
                permOps.add(tpl.ops[i]);
                opToOrder[tpl.ops[i]] = i;
            }
        }
    }
    // Whether to apply hide user / system app filters
    final boolean applyFilters = (packageName == null);
    List<AppOpsManager.PackageOps> pkgs;
    if (packageName != null) {
        pkgs = mAppOps.getOpsForPackage(uid, packageName, tpl.ops);
    } else {
        pkgs = mAppOps.getPackagesForOps(tpl.ops);
    }
    if (pkgs != null) {
        for (int i = 0; i < pkgs.size(); i++) {
            AppOpsManager.PackageOps pkgOps = pkgs.get(i);
            AppEntry appEntry = getAppEntry(context, appEntries, pkgOps.getPackageName(), null, applyFilters);
            if (appEntry == null) {
                continue;
            }
            for (int j = 0; j < pkgOps.getOps().size(); j++) {
                AppOpsManager.OpEntry opEntry = pkgOps.getOps().get(j);
                if (privacyGuard && privacyGuardOps.contains(opEntry.getOp())) {
                    // for this application.
                    if (DEBUG)
                        Log.d(TAG, "Not adding " + AppOpsManager.opToName(opEntry.getOp()) + " (" + opEntry.getOp() + ")");
                    continue;
                }
                addOp(entries, pkgOps, appEntry, opEntry, packageName == null, packageName == null ? 0 : opToOrder[opEntry.getOp()]);
            }
        }
    }
    List<PackageInfo> apps;
    if (packageName != null) {
        apps = new ArrayList<PackageInfo>();
        try {
            PackageInfo pi = mPm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
            apps.add(pi);
        } catch (NameNotFoundException e) {
        }
    } else {
        String[] permsArray = new String[perms.size()];
        perms.toArray(permsArray);
        apps = mPm.getPackagesHoldingPermissions(permsArray, 0);
    }
    for (int i = 0; i < apps.size(); i++) {
        PackageInfo appInfo = apps.get(i);
        AppEntry appEntry = getAppEntry(context, appEntries, appInfo.packageName, appInfo.applicationInfo, applyFilters);
        if (appEntry == null) {
            continue;
        }
        List<AppOpsManager.OpEntry> dummyOps = null;
        AppOpsManager.PackageOps pkgOps = null;
        if (appInfo.requestedPermissions != null) {
            for (int j = 0; j < appInfo.requestedPermissions.length; j++) {
                if (appInfo.requestedPermissionsFlags != null) {
                    if (!privacyGuard && (appInfo.requestedPermissionsFlags[j] & PackageInfo.REQUESTED_PERMISSION_GRANTED) == 0) {
                        if (DEBUG)
                            Log.d(TAG, "Pkg " + appInfo.packageName + " perm " + appInfo.requestedPermissions[j] + " not granted; skipping");
                        continue;
                    }
                }
                if (DEBUG)
                    Log.d(TAG, "Pkg " + appInfo.packageName + ": requested perm " + appInfo.requestedPermissions[j]);
                for (int k = 0; k < perms.size(); k++) {
                    if (!perms.get(k).equals(appInfo.requestedPermissions[j])) {
                        continue;
                    }
                    if (DEBUG)
                        Log.d(TAG, "Pkg " + appInfo.packageName + " perm " + perms.get(k) + " has op " + permOps.get(k) + ": " + appEntry.hasOp(permOps.get(k)));
                    if (appEntry.hasOp(permOps.get(k))) {
                        continue;
                    }
                    if (dummyOps == null) {
                        dummyOps = new ArrayList<AppOpsManager.OpEntry>();
                        pkgOps = new AppOpsManager.PackageOps(appInfo.packageName, appInfo.applicationInfo.uid, dummyOps);
                    }
                    AppOpsManager.OpEntry opEntry = new AppOpsManager.OpEntry(permOps.get(k), AppOpsManager.MODE_ALLOWED, 0, 0, 0, -1, null, 0, 0);
                    dummyOps.add(opEntry);
                    addOp(entries, pkgOps, appEntry, opEntry, packageName == null, packageName == null ? 0 : opToOrder[opEntry.getOp()]);
                }
            }
        }
    }
    // Sort the list.
    Collections.sort(entries, comparator);
    // Done!
    return entries;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Context(android.content.Context) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) PackageInfo(android.content.pm.PackageInfo) AppOpsManager(android.app.AppOpsManager)

Example 22 with AppOpsManager

use of android.app.AppOpsManager in project RxTools by vondear.

the class RxProcessTool method getForegroundProcessName.

/**
 * 获取前台线程包名
 * <p>当不是查看当前App,且SDK大于21时,
 * 需添加权限 {@code <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"/>}</p>
 *
 * @return 前台应用包名
 */
public static String getForegroundProcessName(Context context) {
    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
    if (infos != null && infos.size() != 0) {
        for (ActivityManager.RunningAppProcessInfo info : infos) {
            if (info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return info.processName;
            }
        }
    }
    if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP) {
        PackageManager packageManager = context.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(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) {
                    context.startActivity(intent);
                }
                if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, info.uid, info.packageName) != AppOpsManager.MODE_ALLOWED) {
                    Log.d("getForegroundApp", "没有打开\"有权查看使用权限的应用\"选项");
                    return null;
                }
                UsageStatsManager usageStatsManager = (UsageStatsManager) context.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 {
            Log.d("getForegroundApp", "无\"有权查看使用权限的应用\"选项");
        }
    }
    return null;
}
Also used : ApplicationInfo(android.content.pm.ApplicationInfo) Intent(android.content.Intent) UsageStats(android.app.usage.UsageStats) ActivityManager(android.app.ActivityManager) ResolveInfo(android.content.pm.ResolveInfo) AppOpsManager(android.app.AppOpsManager) PackageManager(android.content.pm.PackageManager) UsageStatsManager(android.app.usage.UsageStatsManager)

Example 23 with AppOpsManager

use of android.app.AppOpsManager in project android_packages_apps_Settings by LineageOS.

the class VpnSettings method getVpnApps.

static List<AppVpnInfo> getVpnApps(Context context, boolean includeProfiles) {
    List<AppVpnInfo> result = Lists.newArrayList();
    final Set<Integer> profileIds;
    if (includeProfiles) {
        profileIds = new ArraySet<>();
        for (UserHandle profile : UserManager.get(context).getUserProfiles()) {
            profileIds.add(profile.getIdentifier());
        }
    } else {
        profileIds = Collections.singleton(UserHandle.myUserId());
    }
    // Fetch VPN-enabled apps from AppOps.
    AppOpsManager aom = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
    List<AppOpsManager.PackageOps> apps = aom.getPackagesForOps(new int[] { OP_ACTIVATE_VPN });
    if (apps != null) {
        for (AppOpsManager.PackageOps pkg : apps) {
            int userId = UserHandle.getUserId(pkg.getUid());
            if (!profileIds.contains(userId)) {
                // Skip packages for users outside of our profile group.
                continue;
            }
            // Look for a MODE_ALLOWED permission to activate VPN.
            boolean allowed = false;
            for (AppOpsManager.OpEntry op : pkg.getOps()) {
                if (op.getOp() == OP_ACTIVATE_VPN && op.getMode() == AppOpsManager.MODE_ALLOWED) {
                    allowed = true;
                }
            }
            if (allowed) {
                result.add(new AppVpnInfo(userId, pkg.getPackageName()));
            }
        }
    }
    Collections.sort(result);
    return result;
}
Also used : AppOpsManager(android.app.AppOpsManager) UserHandle(android.os.UserHandle)

Example 24 with AppOpsManager

use of android.app.AppOpsManager in project android_packages_apps_Settings by LineageOS.

the class DevelopmentSettings method writeMockLocation.

private void writeMockLocation() {
    AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
    // Disable the app op of the previous mock location app if such.
    List<PackageOps> packageOps = appOpsManager.getPackagesForOps(MOCK_LOCATION_APP_OPS);
    if (packageOps != null) {
        // Should be one but in case we are in a bad state due to use of command line tools.
        for (PackageOps packageOp : packageOps) {
            if (packageOp.getOps().get(0).getMode() != AppOpsManager.MODE_ERRORED) {
                String oldMockLocationApp = packageOp.getPackageName();
                try {
                    ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(oldMockLocationApp, PackageManager.GET_DISABLED_COMPONENTS);
                    appOpsManager.setMode(AppOpsManager.OP_MOCK_LOCATION, ai.uid, oldMockLocationApp, AppOpsManager.MODE_ERRORED);
                } catch (NameNotFoundException e) {
                /* ignore */
                }
            }
        }
    }
    // Enable the app op of the new mock location app if such.
    if (!TextUtils.isEmpty(mMockLocationApp)) {
        try {
            ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(mMockLocationApp, PackageManager.GET_DISABLED_COMPONENTS);
            appOpsManager.setMode(AppOpsManager.OP_MOCK_LOCATION, ai.uid, mMockLocationApp, AppOpsManager.MODE_ALLOWED);
        } catch (NameNotFoundException e) {
        /* ignore */
        }
    }
}
Also used : AppOpsManager(android.app.AppOpsManager) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) ApplicationInfo(android.content.pm.ApplicationInfo) PackageOps(android.app.AppOpsManager.PackageOps)

Example 25 with AppOpsManager

use of android.app.AppOpsManager in project android_packages_apps_Settings by LineageOS.

the class DevelopmentSettings method updateMockLocation.

private void updateMockLocation() {
    AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
    List<PackageOps> packageOps = appOpsManager.getPackagesForOps(MOCK_LOCATION_APP_OPS);
    if (packageOps != null) {
        for (PackageOps packageOp : packageOps) {
            if (packageOp.getOps().get(0).getMode() == AppOpsManager.MODE_ALLOWED) {
                mMockLocationApp = packageOps.get(0).getPackageName();
                break;
            }
        }
    }
    if (!TextUtils.isEmpty(mMockLocationApp)) {
        String label = mMockLocationApp;
        try {
            ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(mMockLocationApp, PackageManager.GET_DISABLED_COMPONENTS);
            CharSequence appLabel = getPackageManager().getApplicationLabel(ai);
            if (appLabel != null) {
                label = appLabel.toString();
            }
        } catch (PackageManager.NameNotFoundException e) {
        /* ignore */
        }
        mMockLocationAppPref.setSummary(getString(R.string.mock_location_app_set, label));
        mHaveDebugSettings = true;
    } else {
        mMockLocationAppPref.setSummary(getString(R.string.mock_location_app_not_set));
    }
}
Also used : AppOpsManager(android.app.AppOpsManager) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) PackageManager(android.content.pm.PackageManager) ApplicationInfo(android.content.pm.ApplicationInfo) PackageOps(android.app.AppOpsManager.PackageOps)

Aggregations

AppOpsManager (android.app.AppOpsManager)101 ApplicationInfo (android.content.pm.ApplicationInfo)28 NameNotFoundException (android.content.pm.PackageManager.NameNotFoundException)27 PackageManager (android.content.pm.PackageManager)18 PackageOps (android.app.AppOpsManager.PackageOps)14 ArrayList (java.util.ArrayList)14 UserHandle (android.os.UserHandle)13 IOException (java.io.IOException)10 Context (android.content.Context)9 PackageInfo (android.content.pm.PackageInfo)9 Method (java.lang.reflect.Method)9 TargetApi (android.annotation.TargetApi)8 HashMap (java.util.HashMap)8 RemoteException (android.os.RemoteException)7 ActivityManager (android.app.ActivityManager)6 Intent (android.content.Intent)6 ResolveInfo (android.content.pm.ResolveInfo)6 UserManager (android.os.UserManager)6 VisibleForTesting (com.android.internal.annotations.VisibleForTesting)6 Field (java.lang.reflect.Field)6