Java Code Examples for android.content.Context#checkSelfPermission()

The following examples show how to use android.content.Context#checkSelfPermission() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ControllerFragment.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
private boolean requestFineLocationPermissionIfNeeded() {
    final Context context = getContext();
    if (context == null) return false;

    boolean permissionGranted = true;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // Android Marshmallow Permission check

        if (context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionGranted = false;
            if (mRequestLocationDialog != null) {
                mRequestLocationDialog.cancel();
                mRequestLocationDialog = null;
            }

            final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            mRequestLocationDialog = builder.setTitle(R.string.bluetooth_locationpermission_title)
                    .setMessage(R.string.controller_sensor_locationpermission_text)
                    .setPositiveButton(android.R.string.ok, null)
                    .setOnDismissListener(dialog -> requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_FINE_LOCATION))
                    .show();
        }
    }
    return permissionGranted;
}
 
Example 2
Source File: SignTransactionDialog.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
private static FingerprintManager fingerprintUnlockSupported(Context ctx)
{
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return null;
    }
    if (ctx.checkSelfPermission(Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
        return null;
    }

    FingerprintManager fpManager = (FingerprintManager) ctx.getSystemService(Context.FINGERPRINT_SERVICE);
    if (fpManager == null || !fpManager.isHardwareDetected() || !fpManager.hasEnrolledFingerprints()) {
        return null;
    }

    return fpManager;
}
 
Example 3
Source File: PhoneHelper.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
public static Uri getProfilePictureUri(Context context) {
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context.checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
		return null;
	}
	final String[] projection = new String[]{Profile._ID, Profile.PHOTO_URI};
	final Cursor cursor;
	try {
		cursor = context.getContentResolver().query(Profile.CONTENT_URI, projection, null, null, null);
	} catch (Throwable e) {
		return null;
	}
	if (cursor == null) {
		return null;
	}
	final String uri = cursor.moveToFirst() ? cursor.getString(1) : null;
	cursor.close();
	return uri == null ? null : Uri.parse(uri);
}
 
Example 4
Source File: AvailableDevicesFragment.java    From wearmouse with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    try {
        addPreferencesFromResource(R.xml.prefs_available_devices);
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }

    Context context = getContext();
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    hidDataSender = HidDataSender.getInstance();
    hidDeviceProfile = hidDataSender.register(context, profileListener);

    initiateScanDevices = findPreference(KEY_PREF_BLUETOOTH_SCAN);
    availableDevices = (PreferenceGroup) findPreference(KEY_PREF_BLUETOOTH_AVAILABLE);
    availableDevices.setLayoutResource(R.layout.preference_group_no_title);

    initScanDevices(initiateScanDevices);
    initAvailableDevices();

    registerStateReceiver();

    if (context.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(
                new String[] {Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST);
    }
}
 
Example 5
Source File: DConnectUtil.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * Checks whether permission allow by user.
 *
 * @param context context of application
 * @return Returns true if permission allow, otherwise false
 */
public static boolean isPermission(final Context context) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true;
    } else {
        boolean result = true;
        for (int i = 0; i < PERMISSIONS.length; i++) {
            if (context.checkSelfPermission(PERMISSIONS[i]) != PackageManager.PERMISSION_GRANTED) {
                result = false;
            }
        }
        return result;
    }
}
 
Example 6
Source File: PermissionRecieveSms.java    From geopaparazzi with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean hasPermission(Context context) {
    if (canAskPermission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return context.checkSelfPermission(
                    Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED;
        }
    }
    return true;
}
 
Example 7
Source File: PermissionWriteStorage.java    From geopaparazzi with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean hasPermission(Context context) {
    if (canAskPermission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return context.checkSelfPermission(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        }
    }
    return true;
}
 
Example 8
Source File: ExternalStorageHandler.java    From Lunary-Ethereum-Wallet with GNU General Public License v3.0 5 votes vote down vote up
public static boolean hasPermission(Context c) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (c.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
    } else {
        return true;
    }
    return false;
}
 
Example 9
Source File: CalendarProviderManager.java    From CalendarProviderManager with Apache License 2.0 4 votes vote down vote up
/**
 * 创建一个新的日历账户
 *
 * @return success:ACCOUNT ID , create failed:-1 , permission deny:-2
 */
private static long createCalendarAccount(Context context) {
    // 系统日历表
    Uri uri = CalendarContract.Calendars.CONTENT_URI;

    // 要创建的账户
    Uri accountUri;

    // 开始组装账户数据
    ContentValues account = new ContentValues();
    // 账户类型:本地
    // 在添加账户时,如果账户类型不存在系统中,则可能该新增记录会被标记为脏数据而被删除
    // 设置为ACCOUNT_TYPE_LOCAL可以保证在不存在账户类型时,该新增数据不会被删除
    account.put(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL);
    // 日历在表中的名称
    account.put(CalendarContract.Calendars.NAME, CALENDAR_NAME);
    // 日历账户的名称
    account.put(CalendarContract.Calendars.ACCOUNT_NAME, CALENDAR_ACCOUNT_NAME);
    // 账户显示的名称
    account.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, CALENDAR_DISPLAY_NAME);
    // 日历的颜色
    account.put(CalendarContract.Calendars.CALENDAR_COLOR, Color.parseColor("#515bd4"));
    // 用户对此日历的获取使用权限等级
    account.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER);
    // 设置此日历可见
    account.put(CalendarContract.Calendars.VISIBLE, 1);
    // 日历时区
    account.put(CalendarContract.Calendars.CALENDAR_TIME_ZONE, TimeZone.getDefault().getID());
    // 可以修改日历时区
    account.put(CalendarContract.Calendars.CAN_MODIFY_TIME_ZONE, 1);
    // 同步此日历到设备上
    account.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
    // 拥有者的账户
    account.put(CalendarContract.Calendars.OWNER_ACCOUNT, CALENDAR_ACCOUNT_NAME);
    // 可以响应事件
    account.put(CalendarContract.Calendars.CAN_ORGANIZER_RESPOND, 1);
    // 单个事件设置的最大的提醒数
    account.put(CalendarContract.Calendars.MAX_REMINDERS, 8);
    // 设置允许提醒的方式
    account.put(CalendarContract.Calendars.ALLOWED_REMINDERS, "0,1,2,3,4");
    // 设置日历支持的可用性类型
    account.put(CalendarContract.Calendars.ALLOWED_AVAILABILITY, "0,1,2");
    // 设置日历允许的出席者类型
    account.put(CalendarContract.Calendars.ALLOWED_ATTENDEE_TYPES, "0,1,2");

    /*
        TIP: 修改或添加ACCOUNT_NAME只能由SYNC_ADAPTER调用
        对uri设置CalendarContract.CALLER_IS_SYNCADAPTER为true,即标记当前操作为SYNC_ADAPTER操作
        在设置CalendarContract.CALLER_IS_SYNCADAPTER为true时,必须带上参数ACCOUNT_NAME和ACCOUNT_TYPE(任意)
     */
    uri = uri.buildUpon()
            .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
            .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, CALENDAR_ACCOUNT_NAME)
            .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE,
                    CalendarContract.Calendars.CALENDAR_LOCATION)
            .build();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // 检查日历权限
        if (PackageManager.PERMISSION_GRANTED == context.checkSelfPermission(
                "android.permission.WRITE_CALENDAR")) {
            accountUri = context.getContentResolver().insert(uri, account);
        } else {
            return -2;
        }
    } else {
        accountUri = context.getContentResolver().insert(uri, account);
    }

    return accountUri == null ? -1 : ContentUris.parseId(accountUri);
}
 
Example 10
Source File: PermissionUtils.java    From MNVideoPlayer with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 获取没有授予的权限
 *
 * @param context               上下文对象
 * @param permissions           需要请求的权限组
 */
static ArrayList<String> getFailPermissions(Context context, List<String> permissions) {

    // 如果是安卓6.0以下版本就返回null
    if (!PermissionUtils.isOverMarshmallow()) {
        return null;
    }

    ArrayList<String> failPermissions = null;

    for (String permission : permissions) {

        // 检测安装权限
        if (permission.equals(Permission.REQUEST_INSTALL_PACKAGES)) {

            if (!isHasInstallPermission(context)) {
                if (failPermissions == null) failPermissions = new ArrayList<>();
                failPermissions.add(permission);
            }
            continue;
        }

        // 检测悬浮窗权限
        if (permission.equals(Permission.SYSTEM_ALERT_WINDOW)) {

            if (!isHasOverlaysPermission(context)) {
                if (failPermissions == null) failPermissions = new ArrayList<>();
                failPermissions.add(permission);
            }
            continue;
        }

        // 检测8.0的两个新权限
        if (permission.equals(Permission.ANSWER_PHONE_CALLS) || permission.equals(Permission.READ_PHONE_NUMBERS)) {

            // 检查当前的安卓版本是否符合要求
            if (!isOverOreo()) {
                continue;
            }
        }

        // 把没有授予过的权限加入到集合中
        if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_DENIED) {
            if (failPermissions == null) failPermissions = new ArrayList<>();
            failPermissions.add(permission);
        }
    }

    return failPermissions;
}
 
Example 11
Source File: PermissionUtil.java    From StatusSaver-for-Whatsapp with Apache License 2.0 4 votes vote down vote up
public static boolean hasPermission(Context context, String permission){
    if (useRunTimePermissions()) {
        return context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
    }
    return true;
}
 
Example 12
Source File: PermissionUtility.java    From DeviceConnect-Android with MIT License 4 votes vote down vote up
/**
 * パーミッションの許諾リクエストを要求する.
 *
 * <p>
 * Android OS 6.0以上の端末では、このメソッドが呼び出されると内部でActivityが起動して、ユーザに対してパーミッションの許諾確認を行う。<br>
 * ユーザから許可された場合には、{@link org.deviceconnect.android.activity.PermissionUtility.PermissionRequestCallback#onSuccess}が呼び出され、
 * 拒否された場合には、{@link org.deviceconnect.android.activity.PermissionUtility.PermissionRequestCallback#onFail(String)}が呼び出される。
 * </p>
 * <p>
 * Android OS 6.0未満の端末では、{@link org.deviceconnect.android.activity.PermissionUtility.PermissionRequestCallback#onSuccess}が常に呼び出される。
 * </p>
 * <br>
 * サンプルコード:
 * <pre>
 * {@code
 * String[] permissions = new String[] {
 *     Manifest.permission.ACCESS_COARSE_LOCATION,
 *     Manifest.permission.ACCESS_FINE_LOCATION
 * }
 * 
 * PermissionUtility.requestPermissions(getActivity(), new Handler(),
 *         permissions,
 *         new PermissionUtility.PermissionRequestCallback() {
 *             public void onSuccess() {
 *                 // 許可された時の処理
 *             }
 *             public void onFail(final String deniedPermission) {
 *                 // 拒否された時の処理
 *             }
 *         });
 * }
 * </pre>
 * @param context コンテキスト
 * @param handler ハンドラー
 * @param permissions 許可を求めるパーミッション群
 * @param callback 許諾通知を行うコールバック
 */
public static void requestPermissions(@NonNull final Context context, @NonNull final Handler handler,
        @NonNull final String[] permissions, @NonNull final PermissionRequestCallback callback) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        callback.onSuccess();
    } else {
        Set<String> mPermissionSet = new HashSet<>(Arrays.asList(permissions));

        if (mPermissionSet.size() == 0) {
            callback.onSuccess();
            return;
        }
        Set<String> tmp = new HashSet<>(mPermissionSet);
        for (final String permission : tmp) {
            if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
                mPermissionSet.remove(permission);
            }
        }
        if (mPermissionSet.size() == 0) {
            callback.onSuccess();
        } else {
            String[] missingPermissions = mPermissionSet.toArray(new String[mPermissionSet.size()]);
            PermissionRequestActivity.requestPermissions(context, missingPermissions, new ResultReceiver(handler) {
                @Override
                protected void onReceiveResult(final int resultCode, final Bundle resultData) {
                    String[] retPermissions = resultData.getStringArray(PermissionRequestActivity.EXTRA_PERMISSIONS);
                    int[] retGrantResults = resultData.getIntArray(PermissionRequestActivity.EXTRA_GRANT_RESULTS);
                    if (retPermissions == null || retGrantResults == null) {
                        callback.onFail(null);
                        return;
                    }
                    for (int i = 0; i < retPermissions.length; ++i) {
                        if (retGrantResults[i] == PackageManager.PERMISSION_DENIED) {
                            callback.onFail(retPermissions[i]);
                            return;
                        }
                    }
                    callback.onSuccess();
                }
            });
        }
    }
}
 
Example 13
Source File: PermissionUtils.java    From XXPermissions with Apache License 2.0 4 votes vote down vote up
/**
 * 获取没有授予的权限
 *
 * @param context               上下文对象
 * @param permissions           需要请求的权限组
 */
static ArrayList<String> getFailPermissions(Context context, List<String> permissions) {

    // 如果是安卓6.0以下版本就返回null
    if (!isOverMarshmallow()) {
        return null;
    }

    ArrayList<String> failPermissions = null;

    for (String permission : permissions) {

        // 检测安装权限
        if (Permission.REQUEST_INSTALL_PACKAGES.equals(permission)) {

            if (!isHasInstallPermission(context)) {
                if (failPermissions == null) {
                    failPermissions = new ArrayList<>();
                }
                failPermissions.add(permission);
            }
            continue;
        }

        // 检测悬浮窗权限
        if (Permission.SYSTEM_ALERT_WINDOW.equals(permission)) {

            if (!isHasOverlaysPermission(context)) {
                if (failPermissions == null) {
                    failPermissions = new ArrayList<>();
                }
                failPermissions.add(permission);
            }
            continue;
        }

        // 检测8.0的两个新权限
        if (Permission.ANSWER_PHONE_CALLS.equals(permission) || Permission.READ_PHONE_NUMBERS.equals(permission)) {

            // 检查当前的安卓版本是否符合要求
            if (!isOverOreo()) {
                continue;
            }
        }

        // 把没有授予过的权限加入到集合中
        if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_DENIED) {
            if (failPermissions == null) {
                failPermissions = new ArrayList<>();
            }
            failPermissions.add(permission);
        }
    }

    return failPermissions;
}
 
Example 14
Source File: NonRootUtils.java    From SecondScreen with Apache License 2.0 4 votes vote down vote up
public static boolean hasWriteSecureSettingsPermission(Context context) {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
            && context.checkSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS) == PackageManager.PERMISSION_GRANTED;
}
 
Example 15
Source File: SaveImageProcessor.java    From YCWebView with Apache License 2.0 4 votes vote down vote up
private boolean hasExtStoragePermission(Context context) {
    return Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
            (context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
}
 
Example 16
Source File: Util.java    From NetGuard with GNU General Public License v3.0 4 votes vote down vote up
public static boolean hasPhoneStatePermission(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        return (context.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED);
    else
        return true;
}
 
Example 17
Source File: CropImage.java    From giffun with Apache License 2.0 3 votes vote down vote up
/**
 * Check if the given picked image URI requires READ_EXTERNAL_STORAGE permissions.<br>
 * Only relevant for API version 23 and above and not required for all URI's depends on the
 * implementation of the app that was used for picking the image. So we just test if we can open
 * the stream or do we get an exception when we try, Android is awesome.
 *
 * @param context used to access Android APIs, like content resolve, it is your
 *     activity/fragment/widget.
 * @param uri the result URI of image pick.
 * @return true - required permission are not granted, false - either no need for permissions or
 *     they are granted
 */
public static boolean isReadExternalStoragePermissionsRequired(
    @NonNull Context context, @NonNull Uri uri) {
  return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
      && context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
          != PackageManager.PERMISSION_GRANTED
      && isUriRequiresPermissions(context, uri);
}
 
Example 18
Source File: CropImage.java    From Android-Image-Cropper with Apache License 2.0 3 votes vote down vote up
/**
 * Check if the given picked image URI requires READ_EXTERNAL_STORAGE permissions.<br>
 * Only relevant for API version 23 and above and not required for all URI's depends on the
 * implementation of the app that was used for picking the image. So we just test if we can open
 * the stream or do we get an exception when we try, Android is awesome.
 *
 * @param context used to access Android APIs, like content resolve, it is your
 *     activity/fragment/widget.
 * @param uri the result URI of image pick.
 * @return true - required permission are not granted, false - either no need for permissions or
 *     they are granted
 */
public static boolean isReadExternalStoragePermissionsRequired(
    @NonNull Context context, @NonNull Uri uri) {
  return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
      && context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
          != PackageManager.PERMISSION_GRANTED
      && isUriRequiresPermissions(context, uri);
}
 
Example 19
Source File: SpeechRecognitionPermissions.java    From Android-Speech-Recognition with MIT License 3 votes vote down vote up
Boolean isPermissionGiven(@NonNull Context context){

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            return context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;

        return true; //permission already request on install if < API 23
    }
 
Example 20
Source File: CropImage.java    From Lassi-Android with MIT License 3 votes vote down vote up
/**
 * Check if explicetly requesting camera permission is required.<br>
 * It is required in Android Marshmellow and above if "CAMERA" permission is requested in the
 * manifest.<br>
 * See <a
 * href="http://stackoverflow.com/questions/32789027/android-m-camera-intent-permission-bug">StackOverflow
 * question</a>.
 */
public static boolean isExplicitCameraPermissionRequired(@NonNull Context context) {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
            && hasPermissionInManifest(context, "android.permission.CAMERA")
            && context.checkSelfPermission(Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED;
}