Java Code Examples for androidx.core.app.ActivityCompat#checkSelfPermission()

The following examples show how to use androidx.core.app.ActivityCompat#checkSelfPermission() . These examples are extracted from open source projects. 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
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.location_activity);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION},
                REQUEST_LOCATION_PERMISSION_CODE);
    } else {
        bindLocationListener();
    }
}
 
Example 2
Source Project: PictureSelector   File: PermissionUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 第一次检查权限,用在打开应用的时候请求应用需要的所有权限
 * @param context
 * @param requestCode   请求码
 * @param permission    权限数组
 * @return
 */
public static boolean checkPermissionFirst(Context context , int requestCode, String[] permission){
    List<String> permissions = new ArrayList<String>();
    for (String per : permission) {
        int permissionCode = ActivityCompat.checkSelfPermission(context, per );
        if( permissionCode != PackageManager.PERMISSION_GRANTED ) {
            permissions.add(per);
        }
    }
    if( !permissions.isEmpty() ) {
        ActivityCompat.requestPermissions((Activity) context,permissions.toArray( new String[permissions.size()] ), requestCode);
        return  false;
    }else{
        return  true;
    }
}
 
Example 3
/**
 * 位置情報取得開始.
 * @param accuracy 精度.
 * @param interval 受信間隔.
 */
private void startGPS(final boolean accuracy, final int interval) {
    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(getContext(), ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }

    Criteria criteria = new Criteria();
    if (accuracy) {
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
    } else {
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    }

    mLocationManager.requestLocationUpdates(mLocationManager.getBestProvider(criteria, true), interval, 0, this, Looper.getMainLooper());
}
 
Example 4
public boolean isFingerprintSupported() {

        if (!fingerprintManager.isHardwareDetected()) {
            //Toast.makeText(context, "Your device doesn't support fingerprint authentication", Toast.LENGTH_SHORT).show();
            fingerprintSupported = false;
        }

        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
            //Toast.makeText(context, "Please enable the fingerprint permission", Toast.LENGTH_SHORT).show();
            fingerprintSupported = false;
        }

        if (!fingerprintManager.hasEnrolledFingerprints()) {
            //Toast.makeText(context, "No fingerprint configured. Please register at least one fingerprint in your device's Settings", Toast.LENGTH_SHORT).show();
            fingerprintSupported = false;
        }

        if (!keyguardManager.isKeyguardSecure()) {
            //Toast.makeText(context, "Please enable lockscreen security in your device's Settings", Toast.LENGTH_SHORT).show();
            fingerprintSupported = false;
        }

        return fingerprintSupported;
    }
 
Example 5
private void startScan() {

        if (!hasPermissions() || isScanning) {
            return;
        }

        isScanning = true;
        deviceList.clear();
        bluetoothDevices.clear();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            provisionManager.searchBleEspDevices(deviceNamePrefix, bleScanListener);
            updateProgressAndScanBtn();
        } else {
            Log.e(TAG, "Not able to start scan as Location permission is not granted.");
            Toast.makeText(BLEProvisionLanding.this, "Please give location permission to start BLE scan", Toast.LENGTH_LONG).show();
        }
    }
 
Example 6
private void goToMyLocation()
{
	if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
			ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
	{
		enableMyLocation();
	} else
	{
		googleMap.setMyLocationEnabled(true);
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
		if (location != null)
		{
			googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));
		}
	}
}
 
Example 7
/**
 * Check if file exists and ask user if so.
 */
private void backupToSd() {
	if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
		ActivityCompat.requestPermissions(this,
				new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE_BACKUP);
		return;
	}
	final File backupDir = new File(Environment.getExternalStorageDirectory(), Constants.DATA_DIR);
	final File backupFile = new File(backupDir, BACKUP_FILE);
	if (backupDir == null) {
		Toast.makeText(this, R.string.backup_failed, Toast.LENGTH_LONG).show();
		return;
	}
	if (backupFile.exists()) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		final String msgBackupOverwrite = String.format(
			getString(R.string.backup_overwrite), backupFile);
		builder.setMessage(msgBackupOverwrite)
			.setPositiveButton(android.R.string.ok, (dialog, which) -> {
                   backup(backupFile);
                   dialog.dismiss();
               })
			.setNegativeButton(android.R.string.cancel, null).show();
	} else {
		backup(backupFile);
	}
}
 
Example 8
Source Project: intra42   File: Calendar.java    License: Apache License 2.0 5 votes vote down vote up
private static void addEventToCalendar(Context context, Events event) {

        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        long calID = AppSettings.Notifications.getSelectedCalendar(context);
        long startMillis;
        long endMillis;
        startMillis = event.beginAt.getTime();
        endMillis = event.endAt.getTime();

        ContentResolver cr = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put(CalendarContract.Events.DTSTART, startMillis);
        values.put(CalendarContract.Events.DTEND, endMillis);
        values.put(CalendarContract.Events.TITLE, event.name);
        values.put(CalendarContract.Events.DESCRIPTION, event.description);
        values.put(CalendarContract.Events.CALENDAR_ID, calID);
        values.put(CalendarContract.Events.EVENT_LOCATION, event.location);
        values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getDisplayName());

        values.put(CalendarContract.Events.CUSTOM_APP_PACKAGE, BuildConfig.APPLICATION_ID);
        values.put(CalendarContract.Events.CUSTOM_APP_URI, getEventUri(event.id));

        try {
            cr.insert(CalendarContract.Events.CONTENT_URI, values);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }
 
Example 9
/**
 * Checks if the app has permission to write to device storage
 *
 * <p>If the app does not has permission then the user will be prompted to grant permissions
 *
 * @param activity activity
 */
public static void verifyStoragePermissions(Activity activity, Runnable r) {
  // Check if we have write permission
  int permission =
      ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

  if (permission != PackageManager.PERMISSION_GRANTED) {
    sR = r;
    // We don't have permission so prompt the user
    ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
  } else {
    r.run();
  }
}
 
Example 10
/**
 * Only when the app's target SDK is 23 or higher, it requests each dangerous permissions it
 * needs when the app is running.
 */
private static boolean hasPermissions(Context context, String... permissions) {
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}
 
Example 11
private void captureFileWithPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        if (rc == PackageManager.PERMISSION_GRANTED) {
            captureFiles();
        } else {
            captureFileWithPermission();
        }
    } else {
        captureFiles();
    }
}
 
Example 12
private boolean checkPermissions() {
    if (ActivityCompat.checkSelfPermission(requireContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_PERMISSION);
        return true;
    }
    return false;
}
 
Example 13
private boolean checkPermissions() {
    if (ActivityCompat.checkSelfPermission(this.getContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        fragment.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_PERMISSION);
        return true;
    }
    return false;
}
 
Example 14
private boolean ownPermissionCheck() {

        int permission = ActivityCompat.checkSelfPermission(getActivity(), "android.permission.WRITE_EXTERNAL_STORAGE");
        if (permission != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
        return true;
    }
 
Example 15
/**
 * 判断 Mainifest 中是否包含对应到 permission
 * 如有,则返回 true,反之,则返回 false 并输出日志
 *
 * @param context
 * @param permission
 * @return
 */
public static boolean checkPermission(Context context, String permission) {
  boolean hasPermission =
      (PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(context, permission));
  if (!hasPermission) {
    printErrorLog("permission " + permission + " is missing!");
  }
  return hasPermission;
}
 
Example 16
public void showEmailInput(View view){

        // email suggestion from registered accounts
        ArrayList<String> emails = new ArrayList<>(0);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && view != null) {
                requestPermissions(new String[]{Manifest.permission.GET_ACCOUNTS}, REQUEST_ACCOUNTS_PERMISSION);
                return;
            }
        } else {
            Account[] accounts = AccountManager.get(this).getAccounts();
            for (Account account : accounts) {
                if (Patterns.EMAIL_ADDRESS.matcher(account.name).matches()) {
                    emails.add(account.name);
                }
            }
        }

        SimpleFormDialog.build()
                .fields(Input.email(EMAIL)
                        .required()
                        .suggest(emails)
                        .text(emails.size() > 0 ? emails.get(0) : null),
                        Hint.plain(R.string.email_address_from_accounts)
                )
                .show(this, EMAIL_DIALOG);

        /** Results: {@link MainActivity#onResult} **/

    }
 
Example 17
/**
 * Initializes the UI and creates the detector pipeline.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_qr_code_scan);

    setTitle(R.string.qr_code_scan_title);

    mPreview = findViewById(R.id.preview);
    mGraphicOverlay = findViewById(R.id.graphicOverlay);

    // read parameters from the intent used to launch the activity.
    boolean autoFocus = getIntent().getBooleanExtra(EXTRA_AUTO_FOCUS, false);
    boolean useFlash = getIntent().getBooleanExtra(EXTRA_USE_FLASH, false);

    // Check for the camera permission before accessing the camera.  If the
    // permission is not granted yet, request permission.
    int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
    if (rc == PackageManager.PERMISSION_GRANTED) {
        createCameraSource(autoFocus, useFlash);
    } else {
        requestCameraPermission();
    }

    gestureDetector = new GestureDetector(this, new CaptureGestureListener());
    scaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());

    Snackbar.make(mGraphicOverlay, "Tap to capture. Pinch/Stretch to zoom",
            Snackbar.LENGTH_LONG)
            .show();
}
 
Example 18
@Override
protected void onHandleIntent(@NonNull Intent intent) {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
        Preferences.CALENDAR_INTEGRATION.set("-1");
        return;
    }
    Context context = App.get();
    try {
        ContentResolver cr = context.getContentResolver();


        cr.delete(CalendarContract.Events.CONTENT_URI, CalendarContract.Events.DESCRIPTION + "=\"com.metinkale.prayer\"", null);

        Uri calenderUri = CalendarContract.Calendars.CONTENT_URI.buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, ACCOUNT_NAME)
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, ACCOUNT_TYPE).build();
        cr.delete(calenderUri,
                CalendarContract.Calendars.ACCOUNT_NAME + " = ? AND " + CalendarContract.Calendars.ACCOUNT_TYPE + " = ?",
                new String[]{ACCOUNT_NAME, ACCOUNT_TYPE});

        String id = Preferences.CALENDAR_INTEGRATION.get();

        if ("-1".equals(id)) {
            return;
        }

        List<ContentValues> events = new ArrayList<>();
        long calendarId = getCalendar(context);
        for (int year = HijriDate.getMinGregYear(); year <= HijriDate.getMaxGregYear(); year++) {


            for (Pair<HijriDate, Integer> date : HijriDate.getHolydaysForGregYear(year)) {
                if (date == null || date.second <= 0)
                    continue;
                ContentValues event = new ContentValues();

                event.put(CalendarContract.Events.CALENDAR_ID, calendarId);
                event.put(CalendarContract.Events.TITLE, LocaleUtils.getHolyday(date.second));
                event.put(CalendarContract.Events.DESCRIPTION, "com.metinkale.prayer");
                LocalDate ld = date.first.getLocalDate();
                DateTime cal = ld.toDateTimeAtStartOfDay(DateTimeZone.UTC);

                long dtstart = cal.getMillis();
                long dtend = cal.plusDays(1).getMillis();

                event.put(CalendarContract.Events.DTSTART, dtstart);
                event.put(CalendarContract.Events.DTEND, dtend);
                event.put(CalendarContract.Events.EVENT_TIMEZONE, Time.TIMEZONE_UTC);
                event.put(CalendarContract.Events.STATUS, CalendarContract.Events.STATUS_CONFIRMED);
                event.put(CalendarContract.Events.ALL_DAY, 1);
                event.put(CalendarContract.Events.HAS_ALARM, 0);
                event.put(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_FREE);
                event.put(CalendarContract.Events.CUSTOM_APP_PACKAGE, getPackageName());
                event.put(CalendarContract.Events.CUSTOM_APP_URI, "https://prayerapp.page.link/calendar");


                events.add(event);
            }
        }
        cr.bulkInsert(CalendarContract.Events.CONTENT_URI, events.toArray(new ContentValues[0]));
    } catch (Exception e) {
        Preferences.CALENDAR_INTEGRATION.set("-1");
        Crashlytics.logException(e);
    }

}
 
Example 19
@Override
protected void onHandleIntent(@NonNull Intent intent) {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
        Preferences.CALENDAR_INTEGRATION.set("-1");
        return;
    }
    Context context = App.get();
    try {
        ContentResolver cr = context.getContentResolver();


        cr.delete(CalendarContract.Events.CONTENT_URI, CalendarContract.Events.DESCRIPTION + "=\"com.metinkale.prayer\"", null);

        Uri calenderUri = CalendarContract.Calendars.CONTENT_URI.buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, ACCOUNT_NAME)
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, ACCOUNT_TYPE).build();
        cr.delete(calenderUri,
                CalendarContract.Calendars.ACCOUNT_NAME + " = ? AND " + CalendarContract.Calendars.ACCOUNT_TYPE + " = ?",
                new String[]{ACCOUNT_NAME, ACCOUNT_TYPE});

        String id = Preferences.CALENDAR_INTEGRATION.get();

        if ("-1".equals(id)) {
            return;
        }

        List<ContentValues> events = new ArrayList<>();
        long calendarId = getCalendar(context);
        for (int year = HijriDate.getMinGregYear(); year <= HijriDate.getMaxGregYear(); year++) {


            for (Pair<HijriDate, Integer> date : HijriDate.getHolydaysForGregYear(year)) {
                if (date == null || date.second <= 0)
                    continue;
                ContentValues event = new ContentValues();

                event.put(CalendarContract.Events.CALENDAR_ID, calendarId);
                event.put(CalendarContract.Events.TITLE, LocaleUtils.getHolyday(date.second));
                event.put(CalendarContract.Events.DESCRIPTION, "com.metinkale.prayer");
                LocalDate ld = date.first.getLocalDate();
                DateTime cal = ld.toDateTimeAtStartOfDay(DateTimeZone.UTC);

                long dtstart = cal.getMillis();
                long dtend = cal.plusDays(1).getMillis();

                event.put(CalendarContract.Events.DTSTART, dtstart);
                event.put(CalendarContract.Events.DTEND, dtend);
                event.put(CalendarContract.Events.EVENT_TIMEZONE, Time.TIMEZONE_UTC);
                event.put(CalendarContract.Events.STATUS, CalendarContract.Events.STATUS_CONFIRMED);
                event.put(CalendarContract.Events.ALL_DAY, 1);
                event.put(CalendarContract.Events.HAS_ALARM, 0);
                event.put(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_FREE);
                event.put(CalendarContract.Events.CUSTOM_APP_PACKAGE, getPackageName());
                event.put(CalendarContract.Events.CUSTOM_APP_URI, "https://prayerapp.page.link/calendar");


                events.add(event);
            }
        }
        cr.bulkInsert(CalendarContract.Events.CONTENT_URI, events.toArray(new ContentValues[0]));
    } catch (Exception e) {
        Preferences.CALENDAR_INTEGRATION.set("-1");
        Crashlytics.logException(e);
    }

}
 
Example 20
/**
 * Check if location permissions are granted.
 */
public static boolean hasLocationPermission(Context context) {
  return ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
    ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}