Example usage for android.content Context APP_OPS_SERVICE

List of usage examples for android.content Context APP_OPS_SERVICE

Introduction

In this page you can find the example usage for android.content Context APP_OPS_SERVICE.

Prototype

String APP_OPS_SERVICE

To view the source code for android.content Context APP_OPS_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.app.AppOpsManager for tracking application operations on the device.

Usage

From source file:Main.java

/**
 * Determines whether notifications are enabled for the app represented by |context|.
 * Notifications may be disabled because either the user, or a management tool, has explicitly
 * disallowed the Chrome App to display notifications.
 *
 * This check requires Android KitKat or later. Earlier versions will return an INDETERMINABLE
 * status. When an exception occurs, an EXCEPTION status will be returned instead.
 *
 * @param context The context to check of whether it can show notifications.
 * @return One of the APP_NOTIFICATION_STATUS_* constants defined in this class.
 *//*from   w  w w  . ja  va  2  s  .c  o m*/
@TargetApi(Build.VERSION_CODES.KITKAT)
static int determineAppNotificationStatus(Context context) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
        return APP_NOTIFICATIONS_STATUS_UNDETERMINABLE;
    }

    final String packageName = context.getPackageName();
    final int uid = context.getApplicationInfo().uid;
    final AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);

    try {
        Class appOpsManagerClass = Class.forName(AppOpsManager.class.getName());

        @SuppressWarnings("unchecked")
        final Method checkOpNoThrowMethod = appOpsManagerClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE,
                Integer.TYPE, String.class);

        final Field opPostNotificationField = appOpsManagerClass.getDeclaredField(OP_POST_NOTIFICATION);

        int value = (int) opPostNotificationField.get(Integer.class);
        int status = (int) checkOpNoThrowMethod.invoke(appOpsManager, value, uid, packageName);

        return status == AppOpsManager.MODE_ALLOWED ? APP_NOTIFICATIONS_STATUS_ENABLED
                : APP_NOTIFICATIONS_STATUS_DISABLED;

    } catch (RuntimeException e) {
    } catch (Exception e) {
        // Silently fail here, since this is just collecting statistics. The histogram includes
        // a count for thrown exceptions, if that proves to be significant we can revisit.
    }

    return APP_NOTIFICATIONS_STATUS_EXCEPTION;
}

From source file:nu.yona.app.utils.AppUtils.java

/**
 * Has permission boolean./*from  w ww . j a  va 2 s  .  c o m*/
 *
 * @param context the context
 * @return false if user has not given permission for package access so far.
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
public static boolean hasPermission(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;
    }

}

From source file:com.dena.app.usage.watcher.service.WatchService.java

public void onCreate() {
    super.onCreate();
    try {/*from   www  .  j  a  v  a  2  s . c o  m*/
        final PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(),
                PackageManager.GET_META_DATA);
        mTimer = new Timer(true);
        mTimer.scheduleAtFixedRate(new TimerTask() {
            @TargetApi(Build.VERSION_CODES.KITKAT)
            public void run() {
                if (WatchUtil.isScreenLocked(WatchService.this)) {
                    return;
                }
                try {
                    WatchDatabase db = ((App) getApplication()).getDatabase();
                    if (Build.VERSION_CODES.LOLLIPOP <= Build.VERSION.SDK_INT) {
                        AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
                        if (null != appOpsManager && AppOpsManager.MODE_ALLOWED != appOpsManager.checkOp(
                                AppOpsManager.OPSTR_GET_USAGE_STATS, packageInfo.applicationInfo.uid,
                                getPackageName())) {
                            Intent intent = new Intent(getApplicationContext(), DialogActivity.class);
                            intent.addFlags(WindowManager.LayoutParams.FLAG_LOCAL_FOCUS_MODE
                                    | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                            startActivity(intent);
                            return;
                        }
                    }
                    long time = System.currentTimeMillis();
                    String packageName = WatchUtil.getTopPackageName(WatchService.this);
                    if (null != packageName) {
                        db.addUsageAt(time, packageName);
                        db.addUsageAt(time);
                    }
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }
        }, 0L, 1000L);
        startForeground(R.mipmap.ic_launcher, buildNotification());
    } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
    }
}

From source file:com.android.settings.applications.AppOpsSummary.java

private void resetCounters() {
    final AppOpsManager appOps = (AppOpsManager) mActivity.getSystemService(Context.APP_OPS_SERVICE);
    if (appOps == null) {
        return;/*from  w w  w  . ja v a2 s. c o m*/
    }
    appOps.resetCounters();
    // reload content
    resetAdapter();
}

From source file:com.zte.appopscontrol.applications.AppOpsSummary.java

private void resetCounters() {
    final AppOpsManager appOps = (AppOpsManager) mActivity.getSystemService(Context.APP_OPS_SERVICE);
    if (appOps == null) {
        return;/*from   w w w. ja  va  2s  . co m*/
    }
    //zte test
    //appOps.resetCounters();
    // reload content
    resetAdapter();
}

From source file:com.example.android.commitcontent.app.ImageKeyboard.java

private boolean validatePackageName(@Nullable EditorInfo editorInfo) {
    if (editorInfo == null) {
        return false;
    }/*from w  w w.  j a va2  s . c  o m*/
    final String packageName = editorInfo.packageName;
    if (packageName == null) {
        return false;
    }

    // In Android L MR-1 and prior devices, EditorInfo.packageName is not a reliable identifier
    // of the target application because:
    //   1. the system does not verify it [1]
    //   2. InputMethodManager.startInputInner() had filled EditorInfo.packageName with
    //      view.getContext().getPackageName() [2]
    // [1]: https://android.googlesource.com/platform/frameworks/base/+/a0f3ad1b5aabe04d9eb1df8bad34124b826ab641
    // [2]: https://android.googlesource.com/platform/frameworks/base/+/02df328f0cd12f2af87ca96ecf5819c8a3470dc8
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        return true;
    }

    final InputBinding inputBinding = getCurrentInputBinding();
    if (inputBinding == null) {
        // Due to b.android.com/225029, it is possible that getCurrentInputBinding() returns
        // null even after onStartInputView() is called.
        // TODO: Come up with a way to work around this bug....
        Log.e(TAG,
                "inputBinding should not be null here. " + "You are likely to be hitting b.android.com/225029");
        return false;
    }
    final int packageUid = inputBinding.getUid();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        final AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
        try {
            appOpsManager.checkPackage(packageUid, packageName);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    final PackageManager packageManager = getPackageManager();
    final String possiblePackageNames[] = packageManager.getPackagesForUid(packageUid);
    for (final String possiblePackageName : possiblePackageNames) {
        if (packageName.equals(possiblePackageName)) {
            return true;
        }
    }
    return false;
}

From source file:com.farmerbb.taskbar.MainActivity.java

private void proceedWithAppLaunch(Bundle savedInstanceState) {
    setContentView(R.layout.main);/*from   ww w  .  j a  v  a2  s. c  om*/

    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setCustomView(R.layout.switch_layout);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM);
    }

    theSwitch = (SwitchCompat) findViewById(R.id.the_switch);
    if (theSwitch != null) {
        final SharedPreferences pref = U.getSharedPreferences(this);
        theSwitch.setChecked(pref.getBoolean("taskbar_active", false));

        theSwitch.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                if (U.canDrawOverlays(this)) {
                    boolean firstRun = pref.getBoolean("first_run", true);
                    startTaskbarService();

                    if (firstRun && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !U.isSystemApp(this)) {
                        ApplicationInfo applicationInfo = null;
                        try {
                            applicationInfo = getPackageManager().getApplicationInfo(BuildConfig.APPLICATION_ID,
                                    0);
                        } catch (PackageManager.NameNotFoundException e) {
                            /* Gracefully fail */ }

                        if (applicationInfo != null) {
                            AppOpsManager appOpsManager = (AppOpsManager) 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(MainActivity.this);
                                builder.setTitle(R.string.pref_header_recent_apps)
                                        .setMessage(R.string.enable_recent_apps)
                                        .setPositiveButton(R.string.action_ok, (dialog, which) -> {
                                            try {
                                                startActivity(
                                                        new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
                                                U.showToastLong(MainActivity.this,
                                                        R.string.usage_stats_message);
                                            } catch (ActivityNotFoundException e) {
                                                U.showErrorDialog(MainActivity.this, "GET_USAGE_STATS");
                                            }
                                        }).setNegativeButton(R.string.action_cancel, null);

                                AlertDialog dialog = builder.create();
                                dialog.show();
                            }
                        }
                    }
                } else {
                    U.showPermissionDialog(MainActivity.this);
                    compoundButton.setChecked(false);
                }
            } else
                stopTaskbarService();
        });
    }

    if (savedInstanceState == null) {
        if (!getIntent().hasExtra("theme_change"))
            getFragmentManager().beginTransaction()
                    .replace(R.id.fragmentContainer, new AboutFragment(), "AboutFragment").commit();
        else
            getFragmentManager().beginTransaction()
                    .replace(R.id.fragmentContainer, new AppearanceFragment(), "AppearanceFragment").commit();
    }

    if (!BuildConfig.APPLICATION_ID.equals(BuildConfig.BASE_APPLICATION_ID) && freeVersionInstalled()) {
        final SharedPreferences pref = U.getSharedPreferences(this);
        if (!pref.getBoolean("dont_show_uninstall_dialog", false)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.settings_imported_successfully).setMessage(R.string.import_dialog_message)
                    .setPositiveButton(R.string.action_uninstall, (dialog, which) -> {
                        pref.edit().putBoolean("uninstall_dialog_shown", true).apply();

                        try {
                            startActivity(new Intent(Intent.ACTION_DELETE,
                                    Uri.parse("package:" + BuildConfig.BASE_APPLICATION_ID)));
                        } catch (ActivityNotFoundException e) {
                            /* Gracefully fail */ }
                    });

            if (pref.getBoolean("uninstall_dialog_shown", false))
                builder.setNegativeButton(R.string.action_dont_show_again, (dialogInterface, i) -> pref.edit()
                        .putBoolean("dont_show_uninstall_dialog", true).apply());

            AlertDialog dialog = builder.create();
            dialog.show();
            dialog.setCancelable(false);
        }

        if (!pref.getBoolean("uninstall_dialog_shown", false)) {
            if (theSwitch != null)
                theSwitch.setChecked(false);

            SharedPreferences.Editor editor = pref.edit();

            String iconPack = pref.getString("icon_pack", BuildConfig.BASE_APPLICATION_ID);
            if (iconPack.contains(BuildConfig.BASE_APPLICATION_ID)) {
                editor.putString("icon_pack", BuildConfig.APPLICATION_ID);
            } else {
                U.refreshPinnedIcons(this);
            }

            editor.putBoolean("first_run", true);
            editor.apply();
        }
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
        ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);

        if (shortcutManager.getDynamicShortcuts().size() == 0) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setClass(this, StartTaskbarActivity.class);
            intent.putExtra("is_launching_shortcut", true);

            ShortcutInfo shortcut = new ShortcutInfo.Builder(this, "start_taskbar")
                    .setShortLabel(getString(R.string.start_taskbar))
                    .setIcon(Icon.createWithResource(this, R.drawable.shortcut_icon_start)).setIntent(intent)
                    .build();

            Intent intent2 = new Intent(Intent.ACTION_MAIN);
            intent2.setClass(this, ShortcutActivity.class);
            intent2.putExtra("is_launching_shortcut", true);

            ShortcutInfo shortcut2 = new ShortcutInfo.Builder(this, "freeform_mode")
                    .setShortLabel(getString(R.string.pref_header_freeform))
                    .setIcon(Icon.createWithResource(this, R.drawable.shortcut_icon_freeform))
                    .setIntent(intent2).build();

            shortcutManager.setDynamicShortcuts(Arrays.asList(shortcut, shortcut2));
        }
    }
}

From source file:fabiogentile.powertutor.ui.UMLogger.java

@TargetApi(Build.VERSION_CODES.KITKAT)
boolean hasUsageStatsPermission(Context context) {
    AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
    int mode = appOps.checkOpNoThrow("android:get_usage_stats", android.os.Process.myUid(),
            context.getPackageName());/*from   w  w  w.  j  a va  2  s.c om*/
    boolean granted = mode == AppOpsManager.MODE_ALLOWED;
    return granted;
}

From source file:androidx.core.app.NotificationManagerCompat.java

/**
 * Returns whether notifications from the calling package are not blocked.
 *//*from ww w .j  av  a 2s .co  m*/
public boolean areNotificationsEnabled() {
    if (Build.VERSION.SDK_INT >= 24) {
        return mNotificationManager.areNotificationsEnabled();
    } else if (Build.VERSION.SDK_INT >= 19) {
        AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = mContext.getApplicationInfo();
        String pkg = mContext.getApplicationContext().getPackageName();
        int uid = appInfo.uid;
        try {
            Class<?> appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
                    String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
            int value = (int) opPostNotificationValue.get(Integer.class);
            return ((int) checkOpNoThrowMethod.invoke(appOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
        } catch (ClassNotFoundException | NoSuchMethodException | NoSuchFieldException
                | InvocationTargetException | IllegalAccessException | RuntimeException e) {
            return true;
        }
    } else {
        return true;
    }
}

From source file:com.nick.scalpel.core.AutoFoundWirer.java

private void wireFromContext(Context context, AutoFound.Type type, int idRes, Resources.Theme theme,
        Field field, Object forWho) {
    Resources resources = context.getResources();
    switch (type) {
    case STRING:/*from w w  w  .  j ava 2  s .  co m*/
        setField(field, forWho, resources.getString(idRes));
        break;
    case COLOR:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            setField(field, forWho, resources.getColor(idRes, theme));
        } else {
            //noinspection deprecation
            setField(field, forWho, resources.getColor(idRes));
        }
        break;
    case INTEGER:
        setField(field, forWho, resources.getInteger(idRes));
        break;
    case BOOL:
        setField(field, forWho, resources.getBoolean(idRes));
        break;
    case STRING_ARRAY:
        setField(field, forWho, resources.getStringArray(idRes));
        break;
    case INT_ARRAY:
        setField(field, forWho, resources.getIntArray(idRes));
        break;
    case PM:
        setField(field, forWho, context.getSystemService(Context.POWER_SERVICE));
        break;
    case ACCOUNT:
        setField(field, forWho, context.getSystemService(Context.ACCOUNT_SERVICE));
        break;
    case ALARM:
        setField(field, forWho, context.getSystemService(Context.ALARM_SERVICE));
        break;
    case AM:
        setField(field, forWho, context.getSystemService(Context.ACTIVITY_SERVICE));
        break;
    case WM:
        setField(field, forWho, context.getSystemService(Context.WINDOW_SERVICE));
        break;
    case NM:
        setField(field, forWho, context.getSystemService(Context.NOTIFICATION_SERVICE));
        break;
    case TM:
        setField(field, forWho, context.getSystemService(Context.TELEPHONY_SERVICE));
        break;
    case TCM:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setField(field, forWho, context.getSystemService(Context.TELECOM_SERVICE));
        }
        break;
    case SP:
        setField(field, forWho, PreferenceManager.getDefaultSharedPreferences(context));
        break;
    case PKM:
        setField(field, forWho, context.getPackageManager());
        break;
    case HANDLE:
        setField(field, forWho, new Handler(Looper.getMainLooper()));
        break;
    case ASM:
        setField(field, forWho, context.getSystemService(Context.ACCESSIBILITY_SERVICE));
        break;
    case CAP:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setField(field, forWho, context.getSystemService(Context.CAPTIONING_SERVICE));
        }
        break;
    case KGD:
        setField(field, forWho, context.getSystemService(Context.KEYGUARD_SERVICE));
        break;
    case LOCATION:
        setField(field, forWho, context.getSystemService(Context.LOCATION_SERVICE));
        break;
    case SEARCH:
        setField(field, forWho, context.getSystemService(Context.SEARCH_SERVICE));
        break;
    case SENSOR:
        setField(field, forWho, context.getSystemService(Context.SENSOR_SERVICE));
        break;
    case STORAGE:
        setField(field, forWho, context.getSystemService(Context.STORAGE_SERVICE));
        break;
    case WALLPAPER:
        setField(field, forWho, context.getSystemService(Context.WALLPAPER_SERVICE));
        break;
    case VIBRATOR:
        setField(field, forWho, context.getSystemService(Context.VIBRATOR_SERVICE));
        break;
    case CONNECT:
        setField(field, forWho, context.getSystemService(Context.CONNECTIVITY_SERVICE));
        break;
    case NETWORK_STATUS:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            setField(field, forWho, context.getSystemService(Context.NETWORK_STATS_SERVICE));
        }
        break;
    case WIFI:
        setField(field, forWho, context.getSystemService(Context.WIFI_SERVICE));
        break;
    case AUDIO:
        setField(field, forWho, context.getSystemService(Context.AUDIO_SERVICE));
        break;
    case FP:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            setField(field, forWho, context.getSystemService(Context.FINGERPRINT_SERVICE));
        }
        break;
    case MEDIA_ROUTER:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            setField(field, forWho, context.getSystemService(Context.MEDIA_ROUTER_SERVICE));
        }
        break;
    case SUB:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            setField(field, forWho, context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE));
        }
        break;
    case IME:
        setField(field, forWho, context.getSystemService(Context.INPUT_METHOD_SERVICE));
        break;
    case CLIP_BOARD:
        setField(field, forWho, context.getSystemService(Context.CLIPBOARD_SERVICE));
        break;
    case APP_WIDGET:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setField(field, forWho, context.getSystemService(Context.APPWIDGET_SERVICE));
        }
        break;
    case DEVICE_POLICY:
        setField(field, forWho, context.getSystemService(Context.DEVICE_POLICY_SERVICE));
        break;
    case DOWNLOAD:
        setField(field, forWho, context.getSystemService(Context.DOWNLOAD_SERVICE));
        break;
    case BATTERY:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setField(field, forWho, context.getSystemService(Context.BATTERY_SERVICE));
        }
        break;
    case NFC:
        setField(field, forWho, context.getSystemService(Context.NFC_SERVICE));
        break;
    case DISPLAY:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            setField(field, forWho, context.getSystemService(Context.DISPLAY_SERVICE));
        }
        break;
    case USER:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            setField(field, forWho, context.getSystemService(Context.USER_SERVICE));
        }
        break;
    case APP_OPS:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setField(field, forWho, context.getSystemService(Context.APP_OPS_SERVICE));
        }
        break;
    case BITMAP:
        setField(field, forWho, BitmapFactory.decodeResource(resources, idRes, null));
        break;
    }
}