Search in sources :

Example 71 with AppOpsManager

use of android.app.AppOpsManager in project weiui by kuaifan.

the class ProcessUtils method getForegroundProcessName.

/**
 * 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);
    if (am == null)
        return null;
    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 null;
        }
        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 != null) {
                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 null;
                }
            }
            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 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 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 72 with AppOpsManager

use of android.app.AppOpsManager in project Taskbar by farmerbb.

the class U method showRecentAppsDialog.

public static AlertDialog showRecentAppsDialog(Context context, Runnable onError, Runnable onFinish) {
    Runnable finalOnFinish = onFinish == null ? () -> {
    } : onFinish;
    Runnable finalOnError = onError == null ? () -> showErrorDialog(context, "GET_USAGE_STATS", finalOnFinish) : onError;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !isSystemApp(context)) {
        ApplicationInfo applicationInfo = null;
        try {
            applicationInfo = context.getPackageManager().getApplicationInfo(BuildConfig.APPLICATION_ID, 0);
        } catch (PackageManager.NameNotFoundException e) {
        /* Gracefully fail */
        }
        if (applicationInfo != null) {
            AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName);
            if (mode != AppOpsManager.MODE_ALLOWED) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle(R.string.pref_header_recent_apps).setMessage(R.string.enable_recent_apps).setPositiveButton(R.string.action_ok, (dialog, which) -> {
                    try {
                        context.startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
                        showToastLong(context, R.string.usage_stats_message);
                        finalOnFinish.run();
                    } catch (ActivityNotFoundException e) {
                        finalOnError.run();
                    }
                }).setNegativeButton(R.string.action_cancel, (dialog, which) -> finalOnFinish.run());
                AlertDialog dialog = builder.create();
                dialog.show();
                dialog.setCancelable(false);
                return dialog;
            }
        }
    }
    finalOnFinish.run();
    return null;
}
Also used : AlertDialog(android.app.AlertDialog) Rect(android.graphics.Rect) Arrays(java.util.Arrays) AppOpsManager(android.app.AppOpsManager) Bundle(android.os.Bundle) PackageManager(android.content.pm.PackageManager) StartMenuService(com.farmerbb.taskbar.service.StartMenuService) Uri(android.net.Uri) WindowManager(android.view.WindowManager) LocalBroadcastManager(android.support.v4.content.LocalBroadcastManager) NotificationService(com.farmerbb.taskbar.service.NotificationService) StartTaskbarActivity(com.farmerbb.taskbar.activity.StartTaskbarActivity) Process(android.os.Process) ActivityOptions(android.app.ActivityOptions) Handler(android.os.Handler) ActivityInfo(android.content.pm.ActivityInfo) Display(android.view.Display) View(android.view.View) PowerMenuService(com.farmerbb.taskbar.service.PowerMenuService) Method(java.lang.reflect.Method) TargetApi(android.annotation.TargetApi) Surface(android.view.Surface) Service(android.app.Service) DisplayMetrics(android.util.DisplayMetrics) AlertDialog(android.app.AlertDialog) LauncherApps(android.content.pm.LauncherApps) List(java.util.List) ActivityNotFoundException(android.content.ActivityNotFoundException) LauncherActivityInfo(android.content.pm.LauncherActivityInfo) ShortcutActivity(com.farmerbb.taskbar.activity.ShortcutActivity) ApplicationInfo(android.content.pm.ApplicationInfo) ActivityManager(android.app.ActivityManager) Context(android.content.Context) Intent(android.content.Intent) ArrayList(java.util.ArrayList) DevicePolicyManager(android.app.admin.DevicePolicyManager) UserHandle(android.os.UserHandle) Toast(android.widget.Toast) Settings(android.provider.Settings) LockDeviceReceiver(com.farmerbb.taskbar.receiver.LockDeviceReceiver) Build(android.os.Build) DummyActivity(com.farmerbb.taskbar.activity.DummyActivity) UserManager(android.os.UserManager) BuildConfig(com.farmerbb.taskbar.BuildConfig) R(com.farmerbb.taskbar.R) ComponentName(android.content.ComponentName) ShortcutInfo(android.content.pm.ShortcutInfo) ResolveInfo(android.content.pm.ResolveInfo) Color(android.graphics.Color) TaskbarService(com.farmerbb.taskbar.service.TaskbarService) SharedPreferences(android.content.SharedPreferences) DashboardService(com.farmerbb.taskbar.service.DashboardService) Configuration(android.content.res.Configuration) ContextThemeWrapper(android.support.v7.view.ContextThemeWrapper) InvisibleActivityFreeform(com.farmerbb.taskbar.activity.InvisibleActivityFreeform) Activity(android.app.Activity) AppOpsManager(android.app.AppOpsManager) PackageManager(android.content.pm.PackageManager) ActivityNotFoundException(android.content.ActivityNotFoundException) ApplicationInfo(android.content.pm.ApplicationInfo) Intent(android.content.Intent)

Example 73 with AppOpsManager

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

the class AppOpsState method buildState.

public List<AppOpEntry> buildState(OpsTemplate tpl, int uid, String packageName, Comparator<AppOpEntry> comparator) {
    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];
    for (int i = 0; i < tpl.ops.length; i++) {
        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;
            }
        }
    }
    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);
            if (appEntry == null) {
                continue;
            }
            for (int j = 0; j < pkgOps.getOps().size(); j++) {
                AppOpsManager.OpEntry opEntry = pkgOps.getOps().get(j);
                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);
        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 ((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);
                    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) Context(android.content.Context) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) PackageInfo(android.content.pm.PackageInfo) AppOpsManager(android.app.AppOpsManager)

Example 74 with AppOpsManager

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

the class PictureInPictureDetails method setEnterPipStateForPackage.

/**
 * Sets whether the app associated with the given {@param packageName} is allowed to enter
 * picture-in-picture.
 */
static void setEnterPipStateForPackage(Context context, int uid, String packageName, boolean value) {
    final AppOpsManager appOps = context.getSystemService(AppOpsManager.class);
    final int newMode = value ? MODE_ALLOWED : MODE_ERRORED;
    appOps.setMode(OP_PICTURE_IN_PICTURE, uid, packageName, newMode);
}
Also used : AppOpsManager(android.app.AppOpsManager)

Example 75 with AppOpsManager

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

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