Example usage for android.app AppOpsManager MODE_ALLOWED

List of usage examples for android.app AppOpsManager MODE_ALLOWED

Introduction

In this page you can find the example usage for android.app AppOpsManager MODE_ALLOWED.

Prototype

int MODE_ALLOWED

To view the source code for android.app AppOpsManager MODE_ALLOWED.

Click Source Link

Document

Result from #checkOp , #noteOp , #startOp : the given caller is allowed to perform the given operation.

Usage

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

/**
 * Has permission boolean./*from   www  .j a va 2s . co 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   ww w  .  j a v a  2 s .  c  om
        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.farmerbb.taskbar.MainActivity.java

private void proceedWithAppLaunch(Bundle savedInstanceState) {
    setContentView(R.layout.main);//  w w  w .j a  v  a 2 s .  c o  m

    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 .  ja va  2s.co  m*/
    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 w w  w.j  a va2 s. 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.tomer.alwayson.SettingsFragment.java

private boolean hasUsageAccess() throws PackageManager.NameNotFoundException {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        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;
    } else/*from   w  w  w.  j  ava  2  s  .  c  om*/
        return true;
}

From source file:com.hmatalonga.greenhub.ui.TaskListActivity.java

@TargetApi(21)
private boolean hasSpecialPermission(final 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());/*  w  w  w.  j  av  a 2s.co  m*/
    return mode == AppOpsManager.MODE_ALLOWED;
}

From source file:org.broeuschmeul.android.gps.usb.provider.driver.USBGpsManager.java

public boolean isMockLocationEnabled() {
    // Checks if mock location is enabled in settings

    boolean isMockLocation;

    try {/*from ww w  .  j  a v  a2 s  . c o m*/
        //If marshmallow or higher then we need to check that this app is set as the provider
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            AppOpsManager opsManager = (AppOpsManager) appContext.getSystemService(Context.APP_OPS_SERVICE);
            isMockLocation = opsManager.checkOp(AppOpsManager.OPSTR_MOCK_LOCATION, android.os.Process.myUid(),
                    BuildConfig.APPLICATION_ID) == AppOpsManager.MODE_ALLOWED;

        } else {
            // Anything below it then we just need to check the tickbox is checked.
            isMockLocation = !android.provider.Settings.Secure
                    .getString(appContext.getContentResolver(), "mock_location").equals("0");
        }

    } catch (Exception e) {
        return false;
    }

    return isMockLocation;
}

From source file:com.nbplus.vbroadlauncher.HomeLauncherActivity.java

protected boolean checkAccessedUsageStats() {
    try {/*from   w  w w  .  j  av a  2  s . com*/
        PackageManager packageManager = getPackageManager();
        ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);
        AppOpsManager appOpsManager = (AppOpsManager) 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 false;
    }
}