androidx.core.content.PermissionChecker Java Examples
The following examples show how to use
androidx.core.content.PermissionChecker.
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: Game.java From remixed-dungeon with GNU General Public License v3.0 | 6 votes |
public void doPermissionsRequest(@NotNull 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); } }
Example #2
Source File: public_func.java From telegram-sms with BSD 3-Clause "New" or "Revised" License | 6 votes |
static void send_fallback_sms(Context context, String content, int sub_id) { final String TAG = "send_fallback_sms"; if (androidx.core.content.PermissionChecker.checkSelfPermission(context, Manifest.permission.SEND_SMS) != PermissionChecker.PERMISSION_GRANTED) { Log.d(TAG, "No permission."); return; } SharedPreferences sharedPreferences = context.getSharedPreferences("data", Context.MODE_PRIVATE); String trust_number = sharedPreferences.getString("trusted_phone_number", null); if (trust_number == null) { Log.i(TAG, "The trusted number is empty."); return; } if (!sharedPreferences.getBoolean("fallback_sms", false)) { Log.i(TAG, "Did not open the SMS to fall back."); return; } android.telephony.SmsManager sms_manager; if (sub_id == -1) { sms_manager = SmsManager.getDefault(); } else { sms_manager = SmsManager.getSmsManagerForSubscriptionId(sub_id); } ArrayList<String> divideContents = sms_manager.divideMessage(content); sms_manager.sendMultipartTextMessage(trust_number, null, divideContents, null, null); }
Example #3
Source File: DexterInstance.java From Dexter with Apache License 2.0 | 6 votes |
private PermissionStates getPermissionStates(Collection<String> pendingPermissions) { PermissionStates permissionStates = new PermissionStates(); for (String permission : pendingPermissions) { int permissionState = checkSelfPermission(activity, permission); switch (permissionState) { case PermissionChecker.PERMISSION_DENIED_APP_OP: permissionStates.addImpossibleToGrantPermission(permission); break; case PermissionChecker.PERMISSION_DENIED: permissionStates.addDeniedPermission(permission); break; case PermissionChecker.PERMISSION_GRANTED: default: permissionStates.addGrantedPermission(permission); break; } } return permissionStates; }
Example #4
Source File: DexterActivity.java From Dexter with Apache License 2.0 | 6 votes |
@Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { Collection<String> grantedPermissions = new LinkedList<>(); Collection<String> deniedPermissions = new LinkedList<>(); if (isTargetSdkUnderAndroidM()) { deniedPermissions.addAll(Arrays.asList(permissions)); } else { for (int i = 0; i < permissions.length; i++) { String permission = permissions[i]; switch (grantResults[i]) { case PermissionChecker.PERMISSION_DENIED: case PermissionChecker.PERMISSION_DENIED_APP_OP: deniedPermissions.add(permission); break; case PermissionChecker.PERMISSION_GRANTED: grantedPermissions.add(permission); break; default: } } } Dexter.onPermissionsRequested(grantedPermissions, deniedPermissions); }
Example #5
Source File: BaseActivity.java From react-native-photo-editor with Apache License 2.0 | 6 votes |
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); } }
Example #6
Source File: PhotoEditorActivity.java From react-native-photo-editor with Apache License 2.0 | 6 votes |
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE_GALLERY) { // If request is cancelled, the result arrays are empty. int permissionCheck = PermissionChecker.checkCallingOrSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permissionCheck == PackageManager.PERMISSION_GRANTED) { returnBackWithSavedImage(); } else { // permission denied, boo! Disable the // functionality that depends on this permission. Toast.makeText(this, getString(R.string.media_access_denied_msg), Toast.LENGTH_SHORT).show(); } return; } }
Example #7
Source File: PeriodicEpgSyncJobServiceTest.java From xipl with Apache License 2.0 | 6 votes |
@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."); } }
Example #8
Source File: public_func.java From dingtalk-sms with BSD 3-Clause "New" or "Revised" License | 6 votes |
static String get_contact_name(Context context, String phone_number) { String contact_name = null; if (checkSelfPermission(context, Manifest.permission.READ_CONTACTS) == PermissionChecker.PERMISSION_GRANTED) { try { Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone_number)); String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}; Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { String cursor_name = cursor.getString(0); if (!cursor_name.isEmpty()) contact_name = cursor_name; } cursor.close(); } } catch (Exception e) { e.printStackTrace(); return null; } } return contact_name; }
Example #9
Source File: CameraActivity.java From AndroidAnimationExercise with Apache License 2.0 | 6 votes |
@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 !"; TT.showLToast(mContext, reason); return; } } openCamera(); break; default: break; } }
Example #10
Source File: BlankFragment.java From AndroidAnimationExercise with Apache License 2.0 | 5 votes |
@Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); Optional.ofNullable(getActivity()).ifPresent(fragmentActivity -> { if (PermissionChecker.checkSelfPermission(getActivity(), CONTACTS) == PermissionChecker.PERMISSION_GRANTED) { getLoaderManager().initLoader(0, null, BlankFragment.this); } else { ActivityCompat.requestPermissions(getActivity(), new String[]{CONTACTS}, 100); } }); }
Example #11
Source File: DexterInstance.java From Dexter with Apache License 2.0 | 5 votes |
private boolean isEveryPermissionGranted(Collection<String> permissions, Context context) { for (String permission : permissions) { int permissionState = androidPermissionService.checkSelfPermission(context, permission); if (permissionState != PermissionChecker.PERMISSION_GRANTED) { return false; } } return true; }
Example #12
Source File: ApiLevelTestSuite.java From PermissionsDispatcher with Apache License 2.0 | 5 votes |
@Before public void beforeTest() throws Exception { // Reset the API level assumption this.resetApiLevel(); // Mock out PermissionChecker, so that "checkSelfPermission" // always returns NEEDS_PERMISSION_CHECK. // This way, we can distinguish between auto-grants and permission-checks PowerMockito.mockStatic(PermissionChecker.class); BDDMockito.given(PermissionChecker.checkSelfPermission(any(Context.class), anyString())).willReturn(NEEDS_PERMISSION_CHECK); }
Example #13
Source File: PermissionUtils.java From PermissionsDispatcher with Apache License 2.0 | 5 votes |
/** * Checks all given permissions have been granted. * * @param grantResults results * @return returns true if all permissions have been granted. */ public static boolean verifyPermissions(int... grantResults) { if (grantResults.length == 0) { return false; } for (int result : grantResults) { if (result != PermissionChecker.PERMISSION_GRANTED) { return false; } } return true; }
Example #14
Source File: DataStorageActivity.java From My-MVP with Apache License 2.0 | 5 votes |
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == 100) { if (grantResults[0] == PermissionChecker.PERMISSION_GRANTED) { readContacts(); } else { Toast.makeText(mContext, "Permission denied !", Toast.LENGTH_SHORT).show(); } } super.onRequestPermissionsResult(requestCode, permissions, grantResults); }
Example #15
Source File: CameraActivity.java From AndroidAnimationExercise with Apache License 2.0 | 5 votes |
private boolean hasPermission(String[] permissions) { for (String permission : permissions) { if (ContextCompat.checkSelfPermission(mContext, permission) == PermissionChecker.PERMISSION_DENIED) { return false; } } return true; }
Example #16
Source File: BlankFragment.java From AndroidAnimationExercise with Apache License 2.0 | 5 votes |
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == 100) { if (grantResults[0] == PermissionChecker.PERMISSION_GRANTED) { getLoaderManager().initLoader(0, null, this); } else { Toast.makeText(getContext(), "Permission denied !", Toast.LENGTH_SHORT).show(); } } super.onRequestPermissionsResult(requestCode, permissions, grantResults); }
Example #17
Source File: RecordPermissionHelper.java From LingoRecorder with Apache License 2.0 | 5 votes |
public boolean checkRecordPermission() { if (PermissionChecker.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED || PermissionChecker.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO) != PermissionChecker.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (activity.shouldShowRequestPermissionRationale( Manifest.permission.WRITE_EXTERNAL_STORAGE) || activity.shouldShowRequestPermissionRationale( Manifest.permission.RECORD_AUDIO)) { new AlertDialog.Builder(activity) .setTitle(R.string.check_permission_title) .setMessage(R.string.check_permission_content) .setCancelable(false) .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { activity.requestPermissions(new String[]{ Manifest.permission .WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO}, REQUEST_CODE_PERMISSION); } } }).show(); } else { activity.requestPermissions( new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO}, REQUEST_CODE_PERMISSION); } } return false; } return true; }
Example #18
Source File: PermissionUtil.java From EasyPhotos with Apache License 2.0 | 5 votes |
public static boolean checkAndRequestPermissionsInActivity(Activity cxt, String... checkPermissions) { boolean isHas = true; List<String> permissions = new ArrayList<>(); for (String checkPermission : checkPermissions) { if (PermissionChecker.checkSelfPermission(cxt, checkPermission) != PackageManager.PERMISSION_GRANTED) { isHas = false; permissions.add(checkPermission); } } if (!isHas) { String[] p = permissions.toArray(new String[permissions.size()]); requestPermissionsInActivity(cxt, Code.REQUEST_PERMISSION, p); } return isHas; }
Example #19
Source File: PagedContactsModule.java From react-native-paged-contacts with MIT License | 4 votes |
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (isReadContactsPermission(requestCode, permissions)) { if (requestPermissionPromise != null) requestPermissionPromise.resolve(grantResults[0] == PermissionChecker.PERMISSION_GRANTED); } }
Example #20
Source File: Util.java From android-notification-log with MIT License | 4 votes |
public static boolean hasPermission(Context context, String permission) { return PermissionChecker.checkSelfPermission(context, permission) == PermissionChecker.PERMISSION_GRANTED; }
Example #21
Source File: PhotoEditorActivity.java From react-native-photo-editor with Apache License 2.0 | 4 votes |
private void returnBackWithSavedImage() { int permissionCheck = PermissionChecker.checkCallingOrSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permissionCheck == PackageManager.PERMISSION_GRANTED) { updateView(View.GONE); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); parentImageRelativeLayout.setLayoutParams(layoutParams); new CountDownTimer(1000, 500) { public void onTick(long millisUntilFinished) { } public void onFinish() { String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageName = "IMG_" + timeStamp + ".jpg"; Intent returnIntent = new Intent(); if (isSDCARDMounted()) { String folderName = "PhotoEditorSDK"; File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), folderName); if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()) { Log.d("PhotoEditorSDK", "Failed to create directory"); } String selectedOutputPath = mediaStorageDir.getPath() + File.separator + imageName; returnIntent.putExtra("imagePath", selectedOutputPath); Log.d("PhotoEditorSDK", "selected camera path " + selectedOutputPath); File file = new File(selectedOutputPath); try { FileOutputStream out = new FileOutputStream(file); if (parentImageRelativeLayout != null) { parentImageRelativeLayout.setDrawingCacheEnabled(true); Bitmap bitmap = parentImageRelativeLayout.getDrawingCache(); Bitmap rotatedBitmap = rotateBitmap(bitmap, imageOrientation, true); rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out); } out.flush(); out.close(); try { ExifInterface exifDest = new ExifInterface(file.getAbsolutePath()); exifDest.setAttribute(ExifInterface.TAG_ORIENTATION, Integer.toString(imageOrientation)); exifDest.saveAttributes(); } catch (IOException e) { e.printStackTrace(); } } catch (Exception var7) { var7.printStackTrace(); } } setResult(Activity.RESULT_OK, returnIntent); finish(); } }.start(); Toast.makeText(this, getString(R.string.save_image_succeed), Toast.LENGTH_SHORT).show(); } else { showPermissionRequest(); } }
Example #22
Source File: ApiLevelTestSuite.java From PermissionsDispatcher with Apache License 2.0 | 4 votes |
@Test public void testCheckSelfPermissionMockWorking() throws Exception { // Check that mocking out PermissionChecker works assertEquals(NEEDS_PERMISSION_CHECK, PermissionChecker.checkSelfPermission(mockContext, "permission")); }
Example #23
Source File: OpenFilePlugin.java From open_file with BSD 3-Clause "New" or "Revised" License | 4 votes |
private boolean hasPermission(String permission) { return ContextCompat.checkSelfPermission(activity, permission) == PermissionChecker.PERMISSION_GRANTED; }
Example #24
Source File: AndroidPermissionService.java From Dexter with Apache License 2.0 | 4 votes |
/** * @see PermissionChecker#checkSelfPermission */ int checkSelfPermission(@NonNull Context context, @NonNull String permission) { return PermissionChecker.checkSelfPermission(context, permission); }
Example #25
Source File: public_func.java From telegram-sms with BSD 3-Clause "New" or "Revised" License | 4 votes |
static void send_sms(Context context, String send_to, String content, int slot, int sub_id) { if (androidx.core.content.PermissionChecker.checkSelfPermission(context, Manifest.permission.SEND_SMS) != PermissionChecker.PERMISSION_GRANTED) { Log.d("send_sms", "No permission."); return; } if (!is_phone_number(send_to)) { write_log(context, "[" + send_to + "] is an illegal phone number"); return; } SharedPreferences sharedPreferences = context.getSharedPreferences("data", Context.MODE_PRIVATE); String bot_token = sharedPreferences.getString("bot_token", ""); String chat_id = sharedPreferences.getString("chat_id", ""); String request_uri = public_func.get_url(bot_token, "sendMessage"); message_json request_body = new message_json(); request_body.chat_id = chat_id; android.telephony.SmsManager sms_manager; if (sub_id == -1) { sms_manager = SmsManager.getDefault(); } else { sms_manager = SmsManager.getSmsManagerForSubscriptionId(sub_id); } String dual_sim = get_dual_sim_card_display(context, slot, sharedPreferences.getBoolean("display_dual_sim_display_name", false)); String send_content = "[" + dual_sim + context.getString(R.string.send_sms_head) + "]" + "\n" + context.getString(R.string.to) + send_to + "\n" + context.getString(R.string.content) + content; String message_id = "-1"; request_body.text = send_content + "\n" + context.getString(R.string.status) + context.getString(R.string.sending); String request_body_raw = new Gson().toJson(request_body); RequestBody body = RequestBody.create(request_body_raw, public_func.JSON); OkHttpClient okhttp_client = public_func.get_okhttp_obj(sharedPreferences.getBoolean("doh_switch", true), Paper.book().read("proxy_config", new proxy_config())); Request request = new Request.Builder().url(request_uri).method("POST", body).build(); Call call = okhttp_client.newCall(request); try { Response response = call.execute(); if (response.code() != 200 || response.body() == null) { throw new IOException(String.valueOf(response.code())); } message_id = get_message_id(Objects.requireNonNull(response.body()).string()); } catch (IOException e) { e.printStackTrace(); public_func.write_log(context, "failed to send message:" + e.getMessage()); } ArrayList<String> divideContents = sms_manager.divideMessage(content); ArrayList<PendingIntent> send_receiver_list = new ArrayList<>(); IntentFilter filter = new IntentFilter("send_sms"); BroadcastReceiver receiver = new sms_send_receiver(); context.getApplicationContext().registerReceiver(receiver, filter); Intent sent_intent = new Intent("send_sms"); sent_intent.putExtra("message_id", message_id); sent_intent.putExtra("message_text", send_content); sent_intent.putExtra("sub_id", sms_manager.getSubscriptionId()); PendingIntent sentIntent = PendingIntent.getBroadcast(context, 0, sent_intent, PendingIntent.FLAG_CANCEL_CURRENT); send_receiver_list.add(sentIntent); sms_manager.sendMultipartTextMessage(send_to, null, divideContents, send_receiver_list, null); }
Example #26
Source File: PermissionUtils.java From PermissionsDispatcher with Apache License 2.0 | 3 votes |
/** * Determine context has access to the given permission. * <p> * This is a workaround for RuntimeException of Parcel#readException. * For more detail, check this issue https://github.com/hotchemi/PermissionsDispatcher/issues/107 * * @param context context * @param permission permission * @return true if context has access to the given permission, false otherwise. * @see #hasSelfPermissions(Context, String...) */ private static boolean hasSelfPermission(Context context, String permission) { try { return PermissionChecker.checkSelfPermission(context, permission) == PermissionChecker.PERMISSION_GRANTED; } catch (RuntimeException t) { return false; } }
Example #27
Source File: PermissionUtils.java From DevUtils with Apache License 2.0 | 2 votes |
/** * 判断是否授予了权限 * @param context {@link Context} * @param permission 待判断权限 * @return {@code true} yes, {@code false} no */ private static boolean isGranted(final Context context, final String permission) { if (context == null || permission == null) return false; // SDK 版本小于 23 则表示直接通过 || 检查是否通过权限 return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || PermissionChecker.PERMISSION_GRANTED == PermissionChecker.checkSelfPermission(context, permission); }