Example usage for android.content.pm PackageManager PERMISSION_GRANTED

List of usage examples for android.content.pm PackageManager PERMISSION_GRANTED

Introduction

In this page you can find the example usage for android.content.pm PackageManager PERMISSION_GRANTED.

Prototype

int PERMISSION_GRANTED

To view the source code for android.content.pm PackageManager PERMISSION_GRANTED.

Click Source Link

Document

Permission check result: this is returned by #checkPermission if the permission has been granted to the given package.

Usage

From source file:com.adamas.client.android.MainActivity.java

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
    case MY_PERMISSIONS_REQUEST_CAMERA: {
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // permission was granted, yay! Do the
            // contacts-related task you need to do.
            IntentIntegrator integrator = new IntentIntegrator(this);
            integrator.initiateScan();//from w  w w . ja v a2s. co  m
        } else {
            // permission denied, boo! Disable the
            // functionality that depends on this permission.
        }
        return;
    }
    // other 'case' lines to check for other
    // permissions this app might request
    }
}

From source file:eu.chainfire.opendelta.UpdateService.java

@SuppressLint("SdCardPath")
private void flashUpdate() {
    if (getPackageManager().checkPermission(PERMISSION_ACCESS_CACHE_FILESYSTEM,
            getPackageName()) != PackageManager.PERMISSION_GRANTED) {
        Logger.d("[%s] required beyond this point", PERMISSION_ACCESS_CACHE_FILESYSTEM);
        return;//ww w.  j  a  va  2  s.  co  m
    }

    if (getPackageManager().checkPermission(PERMISSION_REBOOT,
            getPackageName()) != PackageManager.PERMISSION_GRANTED) {
        Logger.d("[%s] required beyond this point", PERMISSION_REBOOT);
        return;
    }

    String flashFilename = prefs.getString(PREF_READY_FILENAME_NAME, PREF_READY_FILENAME_DEFAULT);
    prefs.edit().putString(PREF_READY_FILENAME_NAME, PREF_READY_FILENAME_DEFAULT).commit();
    if ((flashFilename == null) || !flashFilename.startsWith(config.getPathBase()))
        return;

    // Remove the path to the storage from the filename, so we get a path
    // relative to the root of the storage
    String path_sd = Environment.getExternalStorageDirectory() + File.separator;
    flashFilename = flashFilename.substring(path_sd.length());

    // Find additional ZIPs to flash, strip path to sd
    List<String> extras = config.getFlashAfterUpdateZIPs();
    for (int i = 0; i < extras.size(); i++) {
        extras.set(i, extras.get(i).substring(path_sd.length()));
    }

    try {
        // TWRP - OpenRecoveryScript - the recovery will find the correct
        // storage root for the ZIPs, life is nice and easy.
        //
        // Optionally, we're injecting our own signature verification keys
        // and verifying against those. We place these keys in /cache
        // where only privileged apps can edit, contrary to the storage
        // location of the ZIP itself - anyone can modify the ZIP.
        // As such, flashing the ZIP without checking the whole-file
        // signature coming from a secure location would be a security
        // risk.
        {
            if (config.getInjectSignatureEnable()) {
                FileOutputStream os = new FileOutputStream("/cache/recovery/keys", false);
                try {
                    writeString(os, config.getInjectSignatureKeys());
                } finally {
                    os.close();
                }
                setPermissions("/cache/recovery/keys", 0644, Process.myUid(), 2001 /* AID_CACHE */);
            }

            FileOutputStream os = new FileOutputStream("/cache/recovery/openrecoveryscript", false);
            try {
                if (config.getInjectSignatureEnable()) {
                    writeString(os, "cmd cat /res/keys > /res/keys_org");
                    writeString(os, "cmd cat /cache/recovery/keys > /res/keys");
                    writeString(os, "set tw_signed_zip_verify 1");
                    writeString(os, String.format("install %s", flashFilename));
                    writeString(os, "set tw_signed_zip_verify 0");
                    writeString(os, "cmd cat /res/keys_org > /res/keys");
                    writeString(os, "cmd rm /res/keys_org");
                } else {
                    writeString(os, "set tw_signed_zip_verify 0");
                    writeString(os, String.format("install %s", flashFilename));
                }

                if (!config.getSecureModeCurrent()) {
                    // any program could have placed these ZIPs, so ignore
                    // them in secure mode
                    for (String file : extras) {
                        writeString(os, String.format("install %s", file));
                    }
                }
                writeString(os, "wipe cache");
            } finally {
                os.close();
            }

            setPermissions("/cache/recovery/openrecoveryscript", 0644, Process.myUid(), 2001 /* AID_CACHE */);
        }

        // CWM - ExtendedCommand - provide paths to both internal and
        // external storage locations, it's nigh impossible to know in
        // practice which will be correct, not just because the internal
        // storage location varies based on the external storage being
        // present, but also because it's not uncommon for community-built
        // versions to have them reversed. It'll give some horrible looking
        // results, but it seems to continue installing even if one ZIP
        // fails and produce the wanted result. Better than nothing ...
        //
        // We don't generate a CWM script in secure mode, because it
        // doesn't support checking our custom signatures
        if (!config.getSecureModeCurrent()) {
            FileOutputStream os = new FileOutputStream("/cache/recovery/extendedcommand", false);
            try {
                writeString(os, String.format("install_zip(\"%s%s\");", "/sdcard/", flashFilename));
                writeString(os, String.format("install_zip(\"%s%s\");", "/emmc/", flashFilename));
                for (String file : extras) {
                    writeString(os, String.format("install_zip(\"%s%s\");", "/sdcard/", file));
                    writeString(os, String.format("install_zip(\"%s%s\");", "/emmc/", file));
                }
                writeString(os, "run_program(\"/sbin/busybox\", \"rm\", \"-rf\", \"/cache/*\");");
            } finally {
                os.close();
            }

            setPermissions("/cache/recovery/extendedcommand", 0644, Process.myUid(), 2001 /* AID_CACHE */);
        } else {
            (new File("/cache/recovery/extendedcommand")).delete();
        }

        ((PowerManager) getSystemService(Context.POWER_SERVICE)).reboot("recovery");
    } catch (Exception e) {
        // We have failed to write something. There's not really anything
        // else to do at
        // at this stage than give up. No reason to crash though.
        Logger.ex(e);
    }
}

From source file:com.horizondigital.delta.UpdateService.java

@SuppressLint("SdCardPath")
private void flashUpdate() {
    if (getPackageManager().checkPermission(PERMISSION_ACCESS_CACHE_FILESYSTEM,
            getPackageName()) != PackageManager.PERMISSION_GRANTED) {
        Logger.d("[%s] required beyond this point", PERMISSION_ACCESS_CACHE_FILESYSTEM);
        return;//from  w  ww . j av a2  s .  co m
    }

    if (getPackageManager().checkPermission(PERMISSION_REBOOT,
            getPackageName()) != PackageManager.PERMISSION_GRANTED) {
        Logger.d("[%s] required beyond this point", PERMISSION_REBOOT);
        return;
    }

    String flashFilename = prefs.getString(PREF_READY_FILENAME_NAME, PREF_READY_FILENAME_DEFAULT);
    prefs.edit().putString(PREF_READY_FILENAME_NAME, PREF_READY_FILENAME_DEFAULT).commit();
    if ((flashFilename == null) || !flashFilename.startsWith(path_base))
        return;

    // Remove the path to the storage from the filename, so we get a path
    // relative to the root of the storage
    String path_sd = Environment.getExternalStorageDirectory() + File.separator;
    flashFilename = flashFilename.substring(path_sd.length());

    // Find additional ZIPs to flash
    List<String> extras = new ArrayList<String>();
    {
        File[] files = (new File(path_flash_after_update)).listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.getName().toLowerCase(Locale.ENGLISH).endsWith(".zip")) {
                    String filename = f.getAbsolutePath();
                    if (filename.startsWith(path_base)) {
                        extras.add(filename.substring(path_sd.length()));
                    }
                }
            }
        }
        Collections.sort(extras);
    }

    try {
        // We're using TWRP's openrecoveryscript as primary, and CWM's
        // extendedcommand as fallback. Using AOSP's command would
        // break older TWRPs. extendedcommand is broken on 'official'
        // CWM builds, though.

        // TWRP - OpenRecoveryScript - the recovery will find the correct
        // storage root for the ZIPs,
        // life is nice and easy.
        if ((flashFilename != null) && (!flashFilename.equals(""))) {
            FileOutputStream os = new FileOutputStream("/cache/recovery/openrecoveryscript", false);
            try {
                os.write(String.format("install %s\n", flashFilename).getBytes("UTF-8"));
                for (String file : extras) {
                    os.write(String.format("install %s\n", file).getBytes("UTF-8"));
                }
                os.write(("wipe cache\n").getBytes("UTF-8"));
            } finally {
                os.close();
            }
        }
        setPermissions("/cache/recovery/openrecoveryscript", 0644, Process.myUid(), 2001 /* AID_CACHE */);

        // CWM - ExtendedCommand - provide paths to both internal and
        // external storage locations, it's nigh impossible to know in
        // practice which will be correct, not just because the internal
        // storage location varies based on the external storage being
        // present, but also because it's not uncommon for community-built
        // versions to have them reversed. It'll give some horrible looking
        // results, but it seems to continue installing even if one ZIP
        // fails and produce the wanted result. Better than nothing ...
        if ((flashFilename != null) && (!flashFilename.equals(""))) {
            FileOutputStream os = new FileOutputStream("/cache/recovery/extendedcommand", false);
            try {
                os.write(
                        String.format("install_zip(\"%s%s\");\n", "/sdcard/", flashFilename).getBytes("UTF-8"));
                os.write(String.format("install_zip(\"%s%s\");\n", "/emmc/", flashFilename).getBytes("UTF-8"));
                for (String file : extras) {
                    os.write(String.format("install_zip(\"%s%s\");\n", "/sdcard/", file).getBytes("UTF-8"));
                    os.write(String.format("install_zip(\"%s%s\");\n", "/emmc/", file).getBytes("UTF-8"));
                }
                os.write(
                        ("run_program(\"/sbin/busybox\", \"rm\", \"-rf\", \"/cache/*\");\n").getBytes("UTF-8"));
            } finally {
                os.close();
            }
        }
        setPermissions("/cache/recovery/extendedcommand", 0644, Process.myUid(), 2001 /* AID_CACHE */);

        ((PowerManager) getSystemService(Context.POWER_SERVICE)).reboot("recovery");
    } catch (Exception e) {
        // We have failed to write something. There's not really anything else to do at
        // at this stage than give up. No reason to crash though.
        Logger.ex(e);
    }
}

From source file:android_network.hetnet.vpn_service.ActivitySettings.java

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
    PreferenceScreen screen = getPreferenceScreen();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    boolean granted = (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED);

    if (requestCode == REQUEST_METERED2) {
        prefs.edit().putBoolean("unmetered_2g", granted).apply();
        ((TwoStatePreference) screen.findPreference("unmetered_2g")).setChecked(granted);

    } else if (requestCode == REQUEST_METERED3) {
        prefs.edit().putBoolean("unmetered_3g", granted).apply();
        ((TwoStatePreference) screen.findPreference("unmetered_3g")).setChecked(granted);

    } else if (requestCode == REQUEST_METERED4) {
        prefs.edit().putBoolean("unmetered_4g", granted).apply();
        ((TwoStatePreference) screen.findPreference("unmetered_4g")).setChecked(granted);

    } else if (requestCode == REQUEST_ROAMING_NATIONAL) {
        prefs.edit().putBoolean("national_roaming", granted).apply();
        ((TwoStatePreference) screen.findPreference("national_roaming")).setChecked(granted);

    } else if (requestCode == REQUEST_ROAMING_INTERNATIONAL) {
        prefs.edit().putBoolean("whitelist_roaming", granted).apply();
        ((TwoStatePreference) screen.findPreference("whitelist_roaming")).setChecked(granted);
    }/*from w w  w  . j  a  v  a 2s. c om*/

    if (granted)
        ServiceSinkhole.reload("permission granted", this);
}

From source file:com.vuze.android.remote.AndroidUtils.java

public static boolean hasPermisssion(@NonNull Context context, @NonNull String permission) {
    PackageManager packageManager = context.getPackageManager();
    try {/* w w  w  .j a v a2  s . c  o m*/
        packageManager.getPermissionInfo(permission, 0);
    } catch (PackageManager.NameNotFoundException e) {
        Log.d("Perms", "requestPermissions: Permission " + permission + " doesn't exist.  Assuming granted.");
        return true;
    }
    return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
}

From source file:co.taqat.call.CallActivity.java

private void showAcceptCallUpdateDialog() {
    final Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    Drawable d = new ColorDrawable(ContextCompat.getColor(this, R.color.colorC));
    d.setAlpha(200);//from   ww  w .  jav a 2s . c o m
    dialog.setContentView(R.layout.dialog);
    dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT);
    dialog.getWindow().setBackgroundDrawable(d);

    TextView customText = (TextView) dialog.findViewById(R.id.customText);
    customText.setText(getResources().getString(R.string.add_video_dialog));
    Button delete = (Button) dialog.findViewById(R.id.delete_button);
    delete.setText(R.string.accept);
    Button cancel = (Button) dialog.findViewById(R.id.cancel);
    cancel.setText(R.string.decline);

    delete.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName());
            Log.i("[Permission] Camera permission is "
                    + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));

            if (camera == PackageManager.PERMISSION_GRANTED) {
                CallActivity.instance().acceptCallUpdate(true);
            } else {
                checkAndRequestPermission(Manifest.permission.CAMERA, PERMISSIONS_REQUEST_CAMERA);
            }

            dialog.dismiss();
        }
    });

    cancel.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            if (CallActivity.isInstanciated()) {
                CallActivity.instance().acceptCallUpdate(false);
            }
            dialog.dismiss();
        }
    });
    dialog.show();
}

From source file:dev.ukanth.ufirewall.Api.java

/**
 * @param ctx application context (mandatory)
 * @return a list of applications//from  w w w .j  av  a2s. c  o m
 */
public static List<PackageInfoData> getApps(Context ctx, GetAppList appList) {

    initSpecial();
    if (applications != null && applications.size() > 0) {
        // return cached instance
        return applications;
    }

    final SharedPreferences defaultPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    final boolean enableVPN = defaultPrefs.getBoolean("enableVPN", false);
    final boolean enableLAN = defaultPrefs.getBoolean("enableLAN", false);
    final boolean enableRoam = defaultPrefs.getBoolean("enableRoam", true);

    final SharedPreferences prefs = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

    final String savedPkg_wifi_uid = prefs.getString(PREF_WIFI_PKG_UIDS, "");
    final String savedPkg_3g_uid = prefs.getString(PREF_3G_PKG_UIDS, "");
    final String savedPkg_roam_uid = prefs.getString(PREF_ROAMING_PKG_UIDS, "");
    final String savedPkg_vpn_uid = prefs.getString(PREF_VPN_PKG_UIDS, "");
    final String savedPkg_lan_uid = prefs.getString(PREF_LAN_PKG_UIDS, "");

    List<Integer> selected_wifi = new ArrayList<Integer>();
    List<Integer> selected_3g = new ArrayList<Integer>();
    List<Integer> selected_roam = new ArrayList<Integer>();
    List<Integer> selected_vpn = new ArrayList<Integer>();
    List<Integer> selected_lan = new ArrayList<Integer>();

    selected_wifi = getListFromPref(savedPkg_wifi_uid);
    selected_3g = getListFromPref(savedPkg_3g_uid);

    if (enableRoam) {
        selected_roam = getListFromPref(savedPkg_roam_uid);
    }
    if (enableVPN) {
        selected_vpn = getListFromPref(savedPkg_vpn_uid);
    }
    if (enableLAN) {
        selected_lan = getListFromPref(savedPkg_lan_uid);
    }
    //revert back to old approach

    //always use the defaul preferences to store cache value - reduces the application usage size
    final SharedPreferences cachePrefs = ctx.getSharedPreferences("AFWallPrefs", Context.MODE_PRIVATE);

    int count = 0;
    try {
        final PackageManager pkgmanager = ctx.getPackageManager();
        final List<ApplicationInfo> installed = pkgmanager
                .getInstalledApplications(PackageManager.GET_META_DATA);
        SparseArray<PackageInfoData> syncMap = new SparseArray<PackageInfoData>();
        final Editor edit = cachePrefs.edit();
        boolean changed = false;
        String name = null;
        String cachekey = null;
        final String cacheLabel = "cache.label.";
        PackageInfoData app = null;
        ApplicationInfo apinfo = null;

        for (int i = 0; i < installed.size(); i++) {
            //for (final ApplicationInfo apinfo : installed) {
            count = count + 1;
            apinfo = installed.get(i);

            if (appList != null) {
                appList.doProgress(count);
            }

            boolean firstseen = false;
            app = syncMap.get(apinfo.uid);
            // filter applications which are not allowed to access the Internet
            if (app == null && PackageManager.PERMISSION_GRANTED != pkgmanager
                    .checkPermission(Manifest.permission.INTERNET, apinfo.packageName)) {
                continue;
            }
            // try to get the application label from our cache - getApplicationLabel() is horribly slow!!!!
            cachekey = cacheLabel + apinfo.packageName;
            name = prefs.getString(cachekey, "");
            if (name.length() == 0) {
                // get label and put on cache
                name = pkgmanager.getApplicationLabel(apinfo).toString();
                edit.putString(cachekey, name);
                changed = true;
                firstseen = true;
            }
            if (app == null) {
                app = new PackageInfoData();
                app.uid = apinfo.uid;
                app.names = new ArrayList<String>();
                app.names.add(name);
                app.appinfo = apinfo;
                app.pkgName = apinfo.packageName;
                syncMap.put(apinfo.uid, app);
            } else {
                app.names.add(name);
            }
            app.firstseen = firstseen;
            // check if this application is selected
            if (!app.selected_wifi && Collections.binarySearch(selected_wifi, app.uid) >= 0) {
                app.selected_wifi = true;
            }
            if (!app.selected_3g && Collections.binarySearch(selected_3g, app.uid) >= 0) {
                app.selected_3g = true;
            }
            if (enableRoam && !app.selected_roam && Collections.binarySearch(selected_roam, app.uid) >= 0) {
                app.selected_roam = true;
            }
            if (enableVPN && !app.selected_vpn && Collections.binarySearch(selected_vpn, app.uid) >= 0) {
                app.selected_vpn = true;
            }
            if (enableLAN && !app.selected_lan && Collections.binarySearch(selected_lan, app.uid) >= 0) {
                app.selected_lan = true;
            }

        }

        List<PackageInfoData> specialData = new ArrayList<PackageInfoData>();
        specialData.add(new PackageInfoData(SPECIAL_UID_ANY, ctx.getString(R.string.all_item),
                "dev.afwall.special.any"));
        specialData.add(new PackageInfoData(SPECIAL_UID_KERNEL, ctx.getString(R.string.kernel_item),
                "dev.afwall.special.kernel"));
        specialData.add(new PackageInfoData(SPECIAL_UID_TETHER, ctx.getString(R.string.tethering_item),
                "dev.afwall.special.tether"));
        //specialData.add(new PackageInfoData(SPECIAL_UID_DNSPROXY, ctx.getString(R.string.dnsproxy_item), "dev.afwall.special.dnsproxy"));
        specialData.add(new PackageInfoData(SPECIAL_UID_NTP, ctx.getString(R.string.ntp_item),
                "dev.afwall.special.ntp"));
        specialData
                .add(new PackageInfoData("root", ctx.getString(R.string.root_item), "dev.afwall.special.root"));
        specialData.add(new PackageInfoData("media", "Media server", "dev.afwall.special.media"));
        specialData.add(new PackageInfoData("vpn", "VPN networking", "dev.afwall.special.vpn"));
        specialData.add(new PackageInfoData("shell", "Linux shell", "dev.afwall.special.shell"));
        specialData.add(new PackageInfoData("gps", "GPS", "dev.afwall.special.gps"));
        specialData.add(new PackageInfoData("adb", "ADB (Android Debug Bridge)", "dev.afwall.special.adb"));

        if (specialApps == null) {
            specialApps = new HashMap<String, Integer>();
        }
        for (int i = 0; i < specialData.size(); i++) {
            app = specialData.get(i);
            specialApps.put(app.pkgName, app.uid);
            //default DNS/NTP
            if (app.uid != -1 && syncMap.get(app.uid) == null) {
                // check if this application is allowed
                if (!app.selected_wifi && Collections.binarySearch(selected_wifi, app.uid) >= 0) {
                    app.selected_wifi = true;
                }
                if (!app.selected_3g && Collections.binarySearch(selected_3g, app.uid) >= 0) {
                    app.selected_3g = true;
                }
                if (enableRoam && !app.selected_roam && Collections.binarySearch(selected_roam, app.uid) >= 0) {
                    app.selected_roam = true;
                }
                if (enableVPN && !app.selected_vpn && Collections.binarySearch(selected_vpn, app.uid) >= 0) {
                    app.selected_vpn = true;
                }
                if (enableLAN && !app.selected_lan && Collections.binarySearch(selected_lan, app.uid) >= 0) {
                    app.selected_lan = true;
                }
                syncMap.put(app.uid, app);
            }
        }

        if (changed) {
            edit.commit();
        }
        /* convert the map into an array */
        applications = new ArrayList<PackageInfoData>();
        for (int i = 0; i < syncMap.size(); i++) {
            applications.add(syncMap.valueAt(i));
        }

        return applications;
    } catch (Exception e) {
        alert(ctx, ctx.getString(R.string.error_common) + e);
    }
    return null;
}

From source file:co.taqat.call.LinphoneActivity.java

public void checkAndRequestPermissionsToSendImage() {
    ArrayList<String> permissionsList = new ArrayList<String>();

    int readExternalStorage = getPackageManager().checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
            getPackageName());/*from www  .j a v  a  2s  .  c o m*/
    Log.i("[Permission] Read external storage permission is "
            + (readExternalStorage == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
    int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName());
    Log.i("[Permission] Camera permission is "
            + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));

    if (readExternalStorage != PackageManager.PERMISSION_GRANTED) {
        if (LinphonePreferences.instance()
                .firstTimeAskingForPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                || ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.READ_EXTERNAL_STORAGE)) {
            Log.i("[Permission] Asking for read external storage");
            permissionsList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
    }
    if (camera != PackageManager.PERMISSION_GRANTED) {
        if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.CAMERA)
                || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            Log.i("[Permission] Asking for camera");
            permissionsList.add(Manifest.permission.CAMERA);
        }
    }
    if (permissionsList.size() > 0) {
        String[] permissions = new String[permissionsList.size()];
        permissions = permissionsList.toArray(permissions);
        ActivityCompat.requestPermissions(this, permissions, 0);
    }
}

From source file:com.commontime.plugin.LocationManager.java

private boolean hasBlueToothPermission() {
    Context context = cordova.getActivity();
    int access = context.checkCallingOrSelfPermission(Manifest.permission.BLUETOOTH);
    int adminAccess = context.checkCallingOrSelfPermission(Manifest.permission.BLUETOOTH_ADMIN);

    return (access == PackageManager.PERMISSION_GRANTED) && (adminAccess == PackageManager.PERMISSION_GRANTED);
}

From source file:co.taqat.call.LinphoneActivity.java

public void checkAndRequestPermission(String permission, int result) {
    int permissionGranted = getPackageManager().checkPermission(permission, getPackageName());
    Log.i("[Permission] " + permission + " is "
            + (permissionGranted == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));

    if (permissionGranted != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
        Log.i("[Permission] Asking for " + permission);
        ActivityCompat.requestPermissions(this, new String[] { permission }, result);
    }//  w ww  .  j  av a  2  s  .  c o m
}