public boolean checkPermission(Context context, String... permission) { boolean nr = true; for (int i = 0; i < permission.length; i++) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // targetSdkVersion >= Android M, we can // use Context#checkSelfPermission nr = context.checkSelfPermission(permission[i]) == PackageManager.PERMISSION_GRANTED; } else { // targetSdkVersion < Android M, we have to use PermissionChecker nr = PermissionChecker.checkSelfPermission(context, permission[i]) == PermissionChecker.PERMISSION_GRANTED; } if (!nr) { break; } } return nr; }
protected void startCameraActivity() { int permissionCheck = PermissionChecker.checkCallingOrSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permissionCheck == PackageManager.PERMISSION_GRANTED) { Intent photoPickerIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getOutputMediaFile()); photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); startActivityForResult( Intent.createChooser(photoPickerIntent, getString(R.string.upload_picker_title)), CAMERA_CODE); } else { showMenu(1); } }
void onRequestPermissionsResult(String permissions[], int[] grantResults, boolean[] shouldShowRequestPermissionRationale) { for (int i = 0, size = permissions.length; i < size; i++) { log("onRequestPermissionsResult " + permissions[i]); // Find the corresponding subject PublishSubject<Permission> subject = mSubjects.get(permissions[i]); if (subject == null) { // No subject found Log.e(RxPermissions.TAG, "RxPermissions.onRequestPermissionsResult invoked but didn't find the corresponding permission request."); return; } mSubjects.remove(permissions[i]); boolean granted = (grantResults[i] == PackageManager.PERMISSION_GRANTED) && (PermissionChecker.checkSelfPermission(getContext(), permissions[i]) == PermissionChecker.PERMISSION_GRANTED); subject.onNext(new Permission(permissions[i], granted, shouldShowRequestPermissionRationale[i])); subject.onComplete(); } }
@Override public void checkTelephonyPermissions() { if(!mRequestPermissions.isEmpty()) { if(ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PermissionChecker.PERMISSION_GRANTED || (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PermissionChecker.PERMISSION_GRANTED)) { mRequestingPermission = mRequestPermissions.get(0); mRequestPermissions.remove(0); PopUp.show((mRequestingPermission == EventCategories.IPC_BLE_NOTIFICATION_INCOMING_CALL) ? getString(R.string.telephony_permission) : getString(R.string.sms_permission), getString(R.string.permissions_needed_title), R.drawable.message_face, R.drawable.blue_btn, PopUp.GIFF_ANIMATION_NONE, PopUp.TYPE_CHOICE, notificationOKHandler, notificationCancelHandler); } } }
@Override public void checkTelephonyPermissions() { if(!requestPermissions.isEmpty()) { if(ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PermissionChecker.PERMISSION_GRANTED || (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PermissionChecker.PERMISSION_GRANTED)) { requestingPermission = requestPermissions.get(0); requestPermissions.remove(0); PopUp.show((requestingPermission == EventCategories.IPC_BLE_NOTIFICATION_INCOMING_CALL) ? getString(R.string .telephony_permission) : getString(R.string.sms_permission), getString(R.string.permissions_needed_title), R.drawable.message_face, R.drawable.blue_btn, PopUp.GIFF_ANIMATION_NONE, PopUp.TYPE_CHOICE, notificationOKHandler, notificationCancelHandler); } } }
/** * 请求权限 */ public void applyPermission(String[] permissions, onRequestPermissionsListener listener) { this.listener = listener; List<String> permissionList = new ArrayList<>(); for (String permission:permissions ) { if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PermissionChecker.PERMISSION_GRANTED){ permissionList.add(permission); } } if(permissionList.isEmpty()){ listener.onSuccess(); }else{ ActivityCompat.requestPermissions(this,permissionList.toArray(new String[permissionList.size()]), WRITE_EXTERNAL_STORAGE); } }
/** * 申请权限回调 */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { List<String> defeatedValue = new ArrayList<>(); switch (requestCode) { case WRITE_EXTERNAL_STORAGE: for (int i = 0; i < grantResults.length; i++) { String value = permissions[i]; if(grantResults[i] != PermissionChecker.PERMISSION_GRANTED){ defeatedValue.add(value); } } if(defeatedValue.isEmpty()){ listener.onSuccess(); }else{ listener.onDefeated(defeatedValue); } break; } }
/** * 请求单个权限 * * @param activity Activity * @param permission 权限 * @param rationale 提示 */ public void checkPermission(final Activity activity, final String permission, String rationale) { if (PermissionChecker.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) { mActivity = activity; if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) { BaseDialog.create(activity) .setTitle(DESC_TITLE) .setContent(rationale) .setPositive(new BaseDialog.OnClickListener() { @Override public void onClick(BaseDialog dialog) { ActivityCompat.requestPermissions(mActivity, new String[]{permission}, REQUEST_CODE); } }) .show(); } else { ActivityCompat.requestPermissions(activity, new String[]{permission}, REQUEST_CODE); } } else { if (mOnGrantedListener != null) mOnGrantedListener.onGranted(); } }
/** * 请求单个权限 * * @param fragment Fragment * @param permission 权限 * @param rationale 提示 */ public void checkPermission(final Fragment fragment, final String permission, String rationale) { if (PermissionChecker.checkSelfPermission(fragment.getActivity(), permission) != PackageManager.PERMISSION_GRANTED) { mActivity = fragment.getActivity(); if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity, permission)) { BaseDialog.create(mActivity) .setTitle(DESC_TITLE) .setContent(rationale) .setPositive(new BaseDialog.OnClickListener() { @Override public void onClick(BaseDialog dialog) { fragment.requestPermissions(new String[]{permission}, REQUEST_CODE); } }) .show(); } else { fragment.requestPermissions(new String[]{permission}, REQUEST_CODE); } } else { if (mOnGrantedListener != null) mOnGrantedListener.onGranted(); } }
/** * Returns true if <code>Activity</code> or <code>Fragment</code> has access to all given permissions. * * @param context context * @param permissions permissions * @return returns true if <code>Activity</code> or <code>Fragment</code> has access to all given permissions. */ @TargetApi(value = Build.VERSION_CODES.M) public static boolean hasSelfPermissions(Context context, String... permissions) { if (permissions == null || permissions.length == 0) { return false; } for (String permission : permissions) { if (permission.equals(Manifest.permission.SYSTEM_ALERT_WINDOW)) { if (!canDrawOverlays(context)) { return false; } } else if (permission.equals(Manifest.permission.WRITE_SETTINGS)) { if (!canWriteSetting(context)) { return false; } } else if (PermissionChecker.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { return false; } } return true; }
public static List<String> findDeniedPermissions(Activity activity, String... permission) { List<String> denyPermissions = new ArrayList<>(); if (!isOverMarshmallow()) { return denyPermissions; } for (String value : permission) { if (value.equals(Manifest.permission.SYSTEM_ALERT_WINDOW)) { if(!canDrawOverlays(activity)) { denyPermissions.add(value); } } else if(value.equals(Manifest.permission.WRITE_SETTINGS)) { if(!canWriteSetting(activity)) { denyPermissions.add(value); } } else if(PermissionChecker.checkSelfPermission(activity, value) != PackageManager.PERMISSION_GRANTED) { denyPermissions.add(value); } } return denyPermissions; }
@Override public void onClick(View view) { mLastSelectedButtonId = view.getId(); if (R.id.radioExternalShare == mRadioGroup.getCheckedRadioButtonId()) { if (PackageManager.PERMISSION_GRANTED != PermissionChecker.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // パーミッション許可ない場合はRuntimePermissionを要求して処理終了 ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_RUNTIME_PERMISSION); return; } } // 読み書き実行 readOrWrite(); }
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case REQUEST_CAMERA: for (int i = 0; i < permissions.length; i++) { if (grantResults[i] == PermissionChecker.PERMISSION_DENIED) { String reason = permissions[i] + " is denied !"; T.showLToast(mContext, reason); return; } } openCamera(); break; default: break; } }
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (grantResults[0] == PermissionChecker.PERMISSION_GRANTED){ subscription.add( getLocation().subscribe( it -> { model.setLocation(new GeoLocation(it.getLatitude(), it.getLongitude())); locationText.setVisibility(View.VISIBLE); locationText.setText(getString(R.string.lat_and_lon, it.getLatitude(), it.getLongitude())); }, Throwable::printStackTrace ) ); } }
/** * 检查权限授权状态 * * @param context * @param permission * @return */ int checkSelfPermission(Context context, String permission) { try { final PackageInfo info = context.getPackageManager().getPackageInfo( context.getPackageName(), 0); int targetSdkVersion = info.applicationInfo.targetSdkVersion; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (targetSdkVersion >= Build.VERSION_CODES.M) { Log.i(TAG, "targetSdkVersion >= Build.VERSION_CODES.M"); return ContextCompat.checkSelfPermission(context, permission); } else { return PermissionChecker.checkSelfPermission(context, permission); } } } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return ContextCompat.checkSelfPermission(context, permission); }
/** * Gives the specified permission to this app, if it is not granted * * @param activity the activity for accessing resources * @param permissionName the permission name to check * @see android.Manifest.permission */ public static void allowPermission(Activity activity, String permissionName) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return; } // if permission is still not granted if (PermissionChecker.checkSelfPermission(activity, permissionName) != PermissionChecker.PERMISSION_GRANTED) { // try get access for permission ActivityCompat.requestPermissions(activity, new String[]{ permissionName }, PERMISSION_GRANTED_CODE); } else { Log.i(TAG, "Permission " + permissionName + " is granted"); } }
/** * Callback for permission requests. If external storage permissions are granted, this will * restart the application. * * @param context The Context * @param requestCode The request code * @param permissions Array of permissions requested * @param grantResults Array of results of the permission requests */ public static void onRequestPermissionsResult(@NonNull Context context, int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch(requestCode) { case REQUEST_LOCATION: for(int i = 0; i < grantResults.length; i++) { if(!Manifest.permission.ACCESS_COARSE_LOCATION.equals(permissions[i])) { continue; } if(grantResults[i] == PermissionChecker.PERMISSION_GRANTED) { PreferenceManager.getDefaultSharedPreferences(context).edit() .putBoolean(FlavordexApp.PREF_DETECT_LOCATION, true).apply(); } } break; } }
@Test public void testGetDeniedPermissions_whenMixPermissionsGrantedAndUngranted_returnUngrantedPermissions() { // Case 3: 2 permissions, 1 ungranted, 1 granted BDDMockito.given( PermissionChecker.checkSelfPermission( any(Context.class), eq(Manifest.permission.WRITE_EXTERNAL_STORAGE) ) ).willReturn(PackageManager.PERMISSION_DENIED); BDDMockito.given( PermissionChecker.checkSelfPermission(any(Context.class), eq(Manifest.permission.READ_SMS)) ).willReturn(PackageManager.PERMISSION_GRANTED); final String[] deniedPermissions = PermissMeUtils.getDeniedPermissions( mockContext, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_SMS ); assertNotNull(deniedPermissions); assertTrue(deniedPermissions.length == 1); assertTrue(deniedPermissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)); }
@Test public void testGetDeniedPermissions_whenAllPermissionsUngranted_returnAllPermissions() { // Case 4: 2 permissions, 2 ungranted BDDMockito.given( PermissionChecker.checkSelfPermission(any(Context.class), anyString()) ).willReturn(PackageManager.PERMISSION_DENIED); String[] deniedPermissions = PermissMeUtils.getDeniedPermissions( mockContext, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_SMS ); assertNotNull(deniedPermissions); assertTrue(deniedPermissions.length == 2); assertTrue(deniedPermissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)); assertTrue(deniedPermissions[1].equals(Manifest.permission.READ_SMS)); }
private void createFloatingWindow() { //检查权限,低于6.0 int p = PermissionChecker.checkSelfPermission(this, Manifest.permission.SYSTEM_ALERT_WINDOW); if (p == PermissionChecker.PERMISSION_DENIED) { Toast.makeText(this, "缺少悬浮窗权限,请配置权限", Toast.LENGTH_SHORT).show(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW}, 0); } } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { //大于6.0 if (!Settings.canDrawOverlays(this)) { Intent intent = new Intent(); intent.setAction(Settings.ACTION_MANAGE_OVERLAY_PERMISSION); startActivity(intent); } else { floatingWindow = new FloatingWindow(this); } } else { floatingWindow = new FloatingWindow(this); } } }
/** * 显示窗口 */ public void show() { int alertWindowPermission = PermissionChecker.checkSelfPermission(mContext, Manifest.permission.SYSTEM_ALERT_WINDOW); if (alertWindowPermission == PermissionChecker.PERMISSION_GRANTED) { mWindowManager.addView(mWindowView, mWindowLayoutParams); isShow = true; } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (Settings.canDrawOverlays(mContext)) { mWindowManager.addView(mWindowView, mWindowLayoutParams); isShow = true; } else { Toast.makeText(mContext, "没有显示悬浮窗权限,请设置允许显示悬浮窗!", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(mContext, "没有显示悬浮窗权限,请设置允许显示悬浮窗!", Toast.LENGTH_SHORT).show(); } } }
/** * Called when there is a new response for a Android Manifest Permission request * * @param requestCode received. * @param permissions the Android Manifest Permissions that were requested * @param grantResults the grant result for each permission * @return the list of Android Manifest Permissions that were declined by the user. */ public List<String> parseRequestResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode != this.lastRequestCode) { Log.d(TAG, String.format("The received Request Code doesn't match the expected one. Was %d but expected %d", requestCode, this.lastRequestCode)); return Arrays.asList(permissions); } else if (permissions.length == 0 && grantResults.length == 0) { Log.w(TAG, "All the required permissions were declined by the user."); return Arrays.asList(permissions); } List<String> declinedPermissions = new ArrayList<>(); for (int i = 0; i < permissions.length; i++) { if (grantResults[i] != PermissionChecker.PERMISSION_GRANTED) { declinedPermissions.add(permissions[i]); } } if (!declinedPermissions.isEmpty()) { Log.w(TAG, String.format("%d permissions were explicitly declined by the user.", declinedPermissions.size())); } return declinedPermissions; }
private void checkPermissionCamera() { int checkPermission = 0; if (Build.VERSION.SDK_INT >= 23) { // checkPermission =ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA); checkPermission = PermissionChecker.checkSelfPermission(this, Manifest.permission.CAMERA); if (checkPermission != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA); } else { isOpenCamera = true; } } else { checkPermission = checkPermission(26); if (checkPermission == AppOpsManager.MODE_ALLOWED) { isOpenCamera = true; } else if (checkPermission == AppOpsManager.MODE_IGNORED) { isOpenCamera = false; displayFrameworkBugMessageAndExit(); } } }
/** * 动态请求权限 * * @param permissions 权限数组 * @param listener 事件回调 */ public final void requestPermission(String[] permissions, PermissionListener listener) { this.listener = listener; if (Build.VERSION.SDK_INT >= 23) {//大于6.0版本动态请求权限 List<String> list = new ArrayList<>(); for (String permission : permissions) { //检查授权 if (PermissionChecker.checkSelfPermission(mActivity, permission) != PackageManager.PERMISSION_GRANTED) { list.add(permission); } } //所有权限都已获取 if (list.isEmpty()) listener.permissionResult(PERMISSION_REQUEST_SUCCESS); else //请求权限 ActivityCompat.requestPermissions(this, list.toArray(new String[list.size()]), PERMISSION_REQUEST_CODE); } else {//小于6.0直接授权 listener.permissionResult(PERMISSION_REQUEST_SUCCESS); } }
public void doPermissionsRequest(@NonNull InterstitialPoint returnTo, String[] permissions) { boolean havePermissions = true; for (String permission : permissions) { int checkResult = ActivityCompat.checkSelfPermission(this, permission); if (checkResult != PermissionChecker.PERMISSION_GRANTED) { havePermissions = false; break; } } if (!havePermissions) { int code = 0; permissionsPoint = returnTo; ActivityCompat.requestPermissions(this, permissions, code); } else { returnTo.returnToWork(true); } }
@Test public void testPeriodicSync() throws InterruptedException { // Do many syncs in a small period of time and make sure they all start // Tests that a sync can be requested LocalBroadcastManager.getInstance(getActivity()).registerReceiver( mSyncStatusChangedReceiver, new IntentFilter(EpgSyncJobService.ACTION_SYNC_STATUS_CHANGED)); // The CountDownLatch decrements every time sync starts mSyncStatusLatch = new CountDownLatch(NUMBER_OF_SYNCS); EpgSyncJobService.cancelAllSyncRequests(getActivity()); // Make sure that we can set up a sync that can persist after boot assertEquals(getActivity().checkSelfPermission(Manifest.permission.RECEIVE_BOOT_COMPLETED), PermissionChecker.PERMISSION_GRANTED); EpgSyncJobService.setUpPeriodicSync(getActivity(), mInputId, new ComponentName(getActivity(), TestJobService.class), SYNC_PERIOD, SYNC_DURATION); // 15m is the lowest period // Wait for every sync to start, with some leeway. long timeoutSeconds = SYNC_PERIOD * (NUMBER_OF_SYNCS + 1); boolean syncStatusLatchComplete = mSyncStatusLatch.await(timeoutSeconds, TimeUnit.MILLISECONDS); if (!syncStatusLatchComplete) { Assert.fail("Syncing did not complete. The remaining count is " + mSyncStatusLatch.getCount() + " after " + timeoutSeconds + " seconds."); } }
@Override protected void onCreate(final Bundle b) { super.onCreate(b); setResult(RESULT_CANCELED); if (Build.VERSION.SDK_INT >= 23 && PermissionChecker .checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED && PermissionChecker .checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION); } else { start(); } }
@Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (PermissionChecker .checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PermissionChecker.PERMISSION_GRANTED || PermissionChecker .checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PermissionChecker.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(Map.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSIONS); } else { showMap(); } }
public void onARSwitchButtonClicked(View v) { if( button_AR.isChecked() == true ) { // OFF → ONのとき // パーミッションを持っているか確認する if (PermissionChecker.checkSelfPermission( RaderActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { // パーミッションをリクエストする permissionManager.requestCameraPermission(); return; } Log.d( "REQUEST PERMISSION", "パーミッション取得済み" ); // ARモード開始 startARMode(); } else { // ON → OFFのとき // ARモード終了 RADER_VALUES.switchARMode( false ); // カメラ開放 mCamera.close(); mCamera = null; // 背景差し替え(imageView表示) backgroundImageView.setVisibility( backgroundImageView.VISIBLE ); // AR用メッセージ非表示 linearLayout_ARMessages.setVisibility( View.GONE ); // レーダー用メッセージ表示 linearLayout_raderMessages.setVisibility( View.VISIBLE ); } }
private void initVibrator() { Context context = actionBar.getContext(); // TODO Ask for Vibrator-permission! if (ContextCompat.checkSelfPermission(actionBar.getContext(), Manifest.permission.VIBRATE) == PermissionChecker.PERMISSION_GRANTED) { vibrator = Vibrator.class.cast(context.getSystemService(Context.VIBRATOR_SERVICE)); } }
/** * 判断权限是否授权 * @param context * @param permissions * @return */ public static boolean hasPermission(@NonNull Context context, @NonNull String... permissions) { for (String per : permissions ) { int result = PermissionChecker.checkSelfPermission(context, per); if ( result != PermissionChecker.PERMISSION_GRANTED) { return false; } } return true; }
@Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); RxView.clicks(mView.findViewById(R.id.button)) .throttleFirst(1, TimeUnit.SECONDS) .compose(mRxPermissions.ensure(Manifest.permission.CAMERA)) .subscribe(new Consumer<Boolean>() { @Override public void accept(@NonNull Boolean aBoolean) throws Exception { if (!aBoolean) { RxPermissions.showDialog(getContext(),getContext().getPackageName(),"未授予相机使用权限"); } } }); RxView.clicks(mView.findViewById(R.id.button2)) .throttleFirst(1, TimeUnit.SECONDS) .subscribe(new Consumer<Object>() { @Override public void accept(@NonNull Object o) throws Exception { switch (PermissionChecker.checkSelfPermission(getContext(), Manifest.permission.CAMERA)) { case PermissionChecker.PERMISSION_DENIED: Toast.makeText(getContext(), "PERMISSION_DENIED拒绝", Toast.LENGTH_SHORT).show(); PermissionsUtils.warn(getContext(), "相机权限获取失败"); break; case PermissionChecker.PERMISSION_DENIED_APP_OP: Toast.makeText(getContext(), "PERMISSION_DENIED_APP_OP拒绝", Toast.LENGTH_SHORT).show(); break; case PermissionChecker.PERMISSION_GRANTED: Toast.makeText(getContext(), "成功", Toast.LENGTH_SHORT).show(); break; default: break; } } }); }
/** * Checks permission for a camera. If permission is granted then start * the camera activity, else show a dialog window to ask for it. */ private void checkPermissionsForCamera() { if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PermissionChecker.PERMISSION_GRANTED) { PopUp.show(getString(R.string.camera_permission), getString(R.string.permissions_needed_title), R.drawable.message_face, R.drawable.blue_btn, PopUp.GIFF_ANIMATION_NONE, PopUp.TYPE_CHOICE, cameraPermissionOKHandler, cameraPermissionCancelHandler); } else { startCameraActivity(); } }
/** * Checks and requests for external storage permissions * if the app is started at the first time. */ private void checkMinimumPermissionsForThisScreen() { //Check reading permissions & writing permission to populate the HEX files & show program list if(mPrefs.getBoolean(FIRST_RUN, true)) { if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED || (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED)) { PopUp.show(getString(R.string.storage_permission_for_samples), getString(R.string.permissions_needed_title), R.drawable.message_face, R.drawable.blue_btn, PopUp.GIFF_ANIMATION_NONE, PopUp.TYPE_CHOICE, diskStoragePermissionOKHandler, diskStoragePermissionCancelHandler); } else { if(mPrefs.getBoolean(FIRST_RUN, true)) { mPrefs.edit().putBoolean(FIRST_RUN, false).apply(); //First Run. Install the Sample applications new Thread(new Runnable() { @Override public void run() { FileUtils.installSamples(); } }).start(); } } } }
/** * Checks if bluetooth permission is granted. If it's not then ask to grant, * proceed with using bluetooth otherwise. */ private void checkBluetoothPermissions() { //TODO: shouldn't it be BLUETOOTH permission? if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PermissionChecker.PERMISSION_GRANTED) { PopUp.show(getString(R.string.location_permission_pairing), getString(R.string.permissions_needed_title), R.drawable.message_face, R.drawable.blue_btn, PopUp.GIFF_ANIMATION_NONE, PopUp.TYPE_CHOICE, bluetoothPermissionOKHandler, bluetoothPermissionCancelHandler); } else { proceedAfterBlePermissionGranted(); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); if (BuildConfig.DEBUG && Build.VERSION.SDK_INT >= 23 && PermissionChecker .checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0); } phHueSDK.setAppName("HueNotifier"); phHueSDK.setDeviceName(android.os.Build.MODEL); phHueSDK.getNotificationManager().registerSDKListener(listener); connectToBridge(); Database db = Database.getInstance(this); rules = db.getRules(); db.close(); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { addRule(); } }); ruleList = (RecyclerView) findViewById(R.id.list); ruleList.setHasFixedSize(false); ruleList.setLayoutManager( new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); ruleAdapter = new RuleAdapter(this); ruleList.setAdapter(ruleAdapter); }
private Location getLastKnownLocation() { Location coarseLoc = null; Location fineLoc = null; if (PermissionChecker.checkSelfPermission(this.mContext, "android.permission.ACCESS_COARSE_LOCATION") == 0) { coarseLoc = getLastKnownLocationForProvider("network"); } if (PermissionChecker.checkSelfPermission(this.mContext, "android.permission.ACCESS_FINE_LOCATION") == 0) { fineLoc = getLastKnownLocationForProvider("gps"); } return (fineLoc == null || coarseLoc == null) ? fineLoc == null ? coarseLoc : fineLoc : fineLoc.getTime() > coarseLoc.getTime() ? fineLoc : coarseLoc; }
@Override public List<Artist> loadInBackground() { List<Artist> artistList = new ArrayList<>(); if (PermissionChecker.checkCallingOrSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) == PermissionChecker.PERMISSION_GRANTED) { Cursor cursor = getContext().getContentResolver().query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI, null, null, null, sortorder); if (cursor != null && cursor.moveToFirst()) { int idCol = cursor.getColumnIndex(BaseColumns._ID); int nameCol = cursor.getColumnIndex(MediaStore.Audio.ArtistColumns.ARTIST); int albumsNbCol = cursor.getColumnIndex(MediaStore.Audio.ArtistColumns.NUMBER_OF_ALBUMS); int tracksNbCol = cursor.getColumnIndex(MediaStore.Audio.ArtistColumns.NUMBER_OF_TRACKS); do { long id = cursor.getLong(idCol); String artistName = cursor.getString(nameCol); int albumCount = cursor.getInt(albumsNbCol); int trackCount = cursor.getInt(tracksNbCol); artistList.add(new Artist(id, artistName, albumCount, trackCount)); } while (cursor.moveToNext()); cursor.close(); } if (cursor == null) { return Collections.emptyList(); } return artistList; } else { return null; } }
@Override public List<Playlist> loadInBackground() { List<Playlist> playlistList = new ArrayList<>(); if (PermissionChecker.checkCallingOrSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) == PermissionChecker.PERMISSION_GRANTED) { Cursor cursor = getContext().getContentResolver().query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, dataCol, "", null, sortorder); if (cursor != null && cursor.moveToFirst()) { int idCol = cursor.getColumnIndex(MediaStore.Audio.Playlists._ID); int nameCol = cursor.getColumnIndex(MediaStore.Audio.Playlists.NAME); do { long id = cursor.getLong(idCol); String name = cursor.getString(nameCol); Playlist playlist = new Playlist(); playlist.setId(id); playlist.setName(name); playlistList.add(playlist); } while (cursor.moveToNext()); cursor.close(); } if (cursor == null) { return Collections.emptyList(); } return playlistList; } else { return null; } }
@Override public List<Artist> loadInBackground() { List<Artist> artistList = new ArrayList<>(); if (PermissionChecker.checkCallingOrSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) == PermissionChecker.PERMISSION_GRANTED) { Cursor cursor = getContext().getContentResolver().query(MediaStore.Audio.Artists.Albums.getContentUri("external", artistID), null, null, null, sortorder); if (cursor != null && cursor.moveToFirst()) { int idCol = cursor.getColumnIndex(BaseColumns._ID); int nameCol = cursor.getColumnIndex(MediaStore.Audio.Artists.Albums.ARTIST); int albumsNbCol = cursor.getColumnIndex(MediaStore.Audio.Artists.Albums.NUMBER_OF_SONGS_FOR_ARTIST); int tracksNbCol = cursor.getColumnIndex(MediaStore.Audio.Artists.Albums.NUMBER_OF_SONGS); do { long id = cursor.getLong(idCol); String artistName = cursor.getString(nameCol); int albumCount = cursor.getInt(albumsNbCol); int trackCount = cursor.getInt(tracksNbCol); artistList.add(new Artist(id, artistName, albumCount, trackCount)); } while (cursor.moveToNext()); cursor.close(); } if (cursor == null) { return Collections.emptyList(); } return artistList; } else { return null; } }