public static boolean checkPermission(Activity activity, String permission, int code) { if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) { ActivityCompat.requestPermissions(activity, new String[] {permission}, code); } else { ActivityCompat.requestPermissions(activity, new String[] {permission}, code); } return false; } return true; }
/** Solicita as permissões */ public static boolean validate(Activity activity, int requestCode, String... permissions) { List<String> list = new ArrayList<String>(); for (String permission : permissions) { // Valida permissão boolean ok = ContextCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_GRANTED; if (!ok) { list.add(permission); } } if (list.isEmpty()) { // Tudo ok, retorna true return true; } // Lista de permissões que falta acesso. String[] newPermissions = new String[list.size()]; list.toArray(newPermissions); // Solicita permissão ActivityCompat.requestPermissions(activity, newPermissions, 1); return false; }
@Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate() + " + this.hashCode()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_nexrad_view); eventBusProvider.getEventBus().register(this); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); // Create the LocationRequest object mLocationRequest = LocationRequest.create() .setPriority(LocationRequest.PRIORITY_LOW_POWER) .setInterval(10 * 60 * 1000) // 10 seconds, in milliseconds .setFastestInterval(1 * 60 * 1000); // 1 second, in milliseconds if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)) { ActivityCompat.requestPermissions(this, INITIAL_PERMS, INITIAL_REQUEST); } if (PreferenceManager.getDefaultSharedPreferences(this) .getString(SettingsActivity.KEY_PREF_NEXRAD_EMAILADDRESS, null) == null) { startSettings(true); } else { if (((NexradApp) getApplication()).getLastKnownLocation() != null) { RadarBitmapView radarView = (RadarBitmapView) findViewById(R.id.radarView); radarView.onEvent( new LocationChangeEvent(((NexradApp) getApplication()).getLastKnownLocation())); } } }
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getLayoutResourceId() != 0) { setContentView(getLayoutResourceId()); } ButterKnife.bind(this); ((LocativeApplication) getApplication()).inject(this); if (mToolbar != null) { setSupportActionBar(mToolbar); mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24px); mToolbar.setNavigationOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION); } } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.location_activity); // Locate UI widgets mStartUpdatesButton = (Button) findViewById(R.id.start_updates_button); mStopUpdatesButton = (Button) findViewById(R.id.stop_updates_button); mLatitudeTextView = (TextView) findViewById(R.id.latitude_text); mLongitudeTextView = (TextView) findViewById(R.id.longitude_text); mLastUpdateTextView = (TextView) findViewById(R.id.last_update_text); // Set labels. mLatitudeLabel = getResources().getString(R.string.latitude_label); mLongitudeLabel = getResources().getString(R.string.longitude_label); mLastUpdateLabel = getResources().getString(R.string.last_update_time_label); mRequestingLocationUpdates = true; // Update values using data stored in the Bundle. updateValuesFromBundle(savedInstanceState); if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_FINE_LOCATION); } // Kick off the process of building a GoogleApiClient and requesting the LocationServices // API. buildGoogleApiClient(); }
private void getPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale( this, Manifest.permission.GET_ACCOUNTS)) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Permission Request"); builder.setMessage( "To bring you timely alerts we would require few permissions such as account details. Please grant the permissions to continue using these features"); builder.setPositiveButton( "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); ActivityCompat.requestPermissions( MainActivity.this, new String[] {Manifest.permission.GET_ACCOUNTS}, MY_PERMISSIONS_REQUEST_GET_ACCOUNTS); } }); builder.create().show(); } else { ActivityCompat.requestPermissions( this, new String[] {Manifest.permission.GET_ACCOUNTS}, MY_PERMISSIONS_REQUEST_GET_ACCOUNTS); } } else { setupUser(); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "MainActivity - onCreate"); // Check that the Permission to read From External storage - if the checkselfPermission is null // than it means that the user has clicked on "Never Ask me again". if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { // Check if we should show the Permission RAtional behind the reason we are asking for the // Permissions if (ActivityCompat.shouldShowRequestPermissionRationale( this, Manifest.permission.READ_EXTERNAL_STORAGE)) { // Show a Fragment that explains why I need this permission } else { ActivityCompat.requestPermissions( this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE_REQUEST_CODE); } } // Create the List from Storage getExternalRootFolderList(); // Conect the Fragment to the Activity listFragment = new FolderViewFragment(); getSupportFragmentManager() .beginTransaction() .add(R.id.fragment_container, listFragment) .commit(); }
@Override public void onClick(View v) { switch (v.getId()) { case R.id.start_speech_button: startListening(); break; case R.id.stop_speech_button: mSpeechRecognizer.stopListening(); break; case R.id.start_camera_button: if (Build.VERSION.SDK_INT >= CAMERA_2_API_LIMIT) { lawg.d("Has camera permission? " + hasPermission(Manifest.permission.CAMERA)); if (hasPermission(Manifest.permission.CAMERA)) { startCamera2(mTextureView.getWidth(), mTextureView.getHeight()); } else { ActivityCompat.requestPermissions( CameraActivity.this, new String[] {Manifest.permission.CAMERA}, CAMERA_PERMISSIONS_REQUEST); } } break; case R.id.stop_camera_button: stopCamera2(); break; case R.id.capture_camera_button: captureStillPicture(); break; } }
void startAvatarTaker() { int permissionCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA); if (permissionCheck == PackageManager.PERMISSION_DENIED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale( getActivity(), Manifest.permission.CAMERA)) { // Show an expanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. Snackbar.make(mView, R.string.grant_perms, Snackbar.LENGTH_LONG).show(); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions( getActivity(), new String[] {Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA); // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an // app-defined int constant. The callback method gets the // result of the request. } } else { startActivityForResult(getPickImageChooserIntent(), 200); } }
/** * Check if we have the GET_ACCOUNTS permission and request it if we do not. * * @return true if we have the permission, false if we do not. */ private boolean checkAccountsPermission() { final String perm = Manifest.permission.GET_ACCOUNTS; int permissionCheck = ContextCompat.checkSelfPermission(getContext(), perm); if (permissionCheck == PackageManager.PERMISSION_GRANTED) { // We have the permission return true; } else if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), perm)) { // Need to show permission rationale, display a snackbar and then request // the permission again when the snackbar is dismissed. Snackbar.make( recViewLogin.findViewById(R.id.login_layout), R.string.contacts_permission_rationale, Snackbar.LENGTH_INDEFINITE) .setAction( android.R.string.ok, new View.OnClickListener() { @Override public void onClick(View v) { // Request the permission again. ActivityCompat.requestPermissions( getActivity(), new String[] {perm}, RC_PERM_GET_ACCOUNTS); } }) .show(); return false; } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(getActivity(), new String[] {perm}, RC_PERM_GET_ACCOUNTS); return false; } }
/** * Handles the requesting of the camera permission. This includes showing a "Snackbar" message of * why the permission is needed then sending the request. */ private void requestCameraPermission() { Log.w(TAG, "Camera permission not granted, requesting..."); final String[] permissions = new String[] {Manifest.permission.CAMERA}; if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { Log.d(TAG, "We do not need to show permission rationale"); ActivityCompat.requestPermissions(this, permissions, RC_HANDLE_CAMERA_PERM); return; } final Activity thisActivity = this; Log.i(TAG, "Showing Request Permissions Rationale"); View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View view) { ActivityCompat.requestPermissions(thisActivity, permissions, RC_HANDLE_CAMERA_PERM); } }; Snackbar.make(mGraphicOverlay, R.string.permission_camera_rationale, Snackbar.LENGTH_INDEFINITE) .setAction(android.R.string.ok, listener) .show(); }
private void checkForStoragePermission(int position, SimpleItemViewHolder holder) { if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { getWallpaper(position); } else { if (ActivityCompat.shouldShowRequestPermissionRationale( (Activity) context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { Snackbar.make( holder.mainView, R.string.permission_storage_rationale, Snackbar.LENGTH_INDEFINITE) .setAction( R.string.ok, new View.OnClickListener() { @Override public void onClick(View view) { ActivityCompat.requestPermissions( (Activity) context, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE); } }) .show(); } else { reqPos = position; ActivityCompat.requestPermissions( ((Activity) context), new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE); } } }
/** Try to get my current location by GPS or Network Provider */ public void getLocation() { try { locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); // getting GPS status isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); // getting network status isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); // Try to get location if you GPS Service is enabled if (isGPSEnabled) { this.isGPSTrackingEnabled = true; // Log.d(TAG, "Application use GPS Service"); /* * This provider determines location using * satellites. Depending on conditions, this provider may take a while to return * a location fix. */ provider_info = LocationManager.GPS_PROVIDER; } else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled this.isGPSTrackingEnabled = true; // Log.d(TAG, "Application use Network State to get GPS coordinates"); /* * This provider determines location based on * availability of cell tower and WiFi access points. Results are retrieved * by means of a network lookup. */ provider_info = LocationManager.NETWORK_PROVIDER; } // Application can use GPS or Network Provider // check permissions if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Log.i("Permission", "not granted -- To be checked"); ActivityCompat.requestPermissions( targActivity, // getParent(), new String[] { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION }, 0); return; } else // Log.i("Permission", "GRANTED"); if (!provider_info.isEmpty()) { // TODO the null is here locationManager.requestLocationUpdates( provider_info, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); if (locationManager != null) { location = locationManager.getLastKnownLocation(provider_info); updateGPSCoordinates(); } } } catch (Exception e) { // e.printStackTrace(); // Log.e(TAG, "Impossible to connect to LocationManager", e); } }
/** Fires the permission rationale dialog or the permission request dialog. */ private void firePermissionRequest() { String locationPermission = Manifest.permission.ACCESS_FINE_LOCATION; if (mRationaleDialog == null) { boolean rationale = ActivityCompat.shouldShowRequestPermissionRationale(this, locationPermission); if (rationale) { // Show the rationale dialog mRationaleDialog = new AlertDialog.Builder(this) .setTitle(R.string.later_location_rationale_title) .setMessage(R.string.later_location_rationale) .setPositiveButton(R.string.later_location_rationale_button, this) .setOnCancelListener(this) .create(); mRationaleDialog.show(); } else { if (SharedPreferencesManager.isFirstLocationPermissionRequest(this)) { // Request permissions SharedPreferencesManager.locationPermissionRequested(this); ActivityCompat.requestPermissions( this, new String[] {locationPermission}, LOCATION_PERMISSION_RC); mRationaleDialog = null; } else { // If this is not the first time but rationale is false, it means that the // user has tapped never ask again. In this case, if the user really // wants this feature he will have to go to settings and enable location // manually, otherwise, this will not work at all. mLocationDisabledDialog = new AlertDialog.Builder(this) .setTitle(R.string.later_location_disabled_title) .setMessage(R.string.later_location_disabled) .setPositiveButton(R.string.later_location_disabled_button_positive, this) .setNegativeButton(R.string.later_location_disabled_button_negative, this) .setOnCancelListener(this) .create(); mLocationDisabledDialog.show(); } } } else { // Request permissions SharedPreferencesManager.locationPermissionRequested(this); ActivityCompat.requestPermissions( this, new String[] {locationPermission}, LOCATION_PERMISSION_RC); mRationaleDialog = null; } }
private static void executePermissionsRequest( Activity activity, String[] perms, int requestCode) { if (!(activity instanceof PermissionCallbacks)) { throw new IllegalArgumentException("Activity must implement PermissionCallbacks."); } ActivityCompat.requestPermissions(activity, perms, requestCode); }
@SuppressWarnings("SameParameterValue") private void perm(String permission, int permission_request) { if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) { if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) { ActivityCompat.requestPermissions(this, new String[] {permission}, permission_request); } } }
/** * Checks if the needed permissions are available * * @return If the permissions are available. If false is returned, the necessary prompts will be * shown */ private boolean checkWritePermissions() { @PermissionUtils.PermissionLevel int permissionLevel = PermissionUtils.getPermissionLevel(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); switch (permissionLevel) { case PermissionUtils.PERMISSION_AVAILABLE: LogUtil.v(TAG, "Permissions available"); return true; case PermissionUtils.PERMISSION_DENIED: new AlertDialog.Builder(getActivity(), app.getImgurTheme().getAlertDialogTheme()) .setTitle(R.string.permission_title) .setMessage(R.string.permission_rationale_upload) .setNegativeButton( R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Snackbar.make(mMultiView, R.string.permission_denied, Snackbar.LENGTH_LONG) .show(); } }) .setPositiveButton( R.string.okay, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ActivityCompat.requestPermissions( getActivity(), new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, RequestCodes.REQUEST_PERMISSION_WRITE); } }) .setOnCancelListener( new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialogInterface) { Snackbar.make(mMultiView, R.string.permission_denied, Snackbar.LENGTH_LONG) .show(); } }) .show(); break; case PermissionUtils.PERMISSION_NEVER_ASKED: default: LogUtil.v(TAG, "Prompting for permissions"); ActivityCompat.requestPermissions( getActivity(), new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, RequestCodes.REQUEST_PERMISSION_WRITE); break; } return false; }
// request storage permission private void requestStoragePermission() { String storagePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE; int hasPermission = ContextCompat.checkSelfPermission(context, storagePermission); String[] permissions = new String[] {storagePermission}; if (hasPermission != PackageManager.PERMISSION_GRANTED) { Log.e(TAG, "No storage permission at the moment. Requesting..."); ActivityCompat.requestPermissions(getActivity(), permissions, REQUEST_STORAGE); } else Log.e(TAG, "We already have storage permission. Yay!"); }
private void attemptToLaunchScanning() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { finishLaunchingScanning(); } else { ActivityCompat.requestPermissions( this, new String[] {Manifest.permission.CAMERA}, REQUEST_CODE_CAMERA_PERMISSION); } }
public void requestInternetPermission() { if (ActivityCompat.shouldShowRequestPermissionRationale( activity, Manifest.permission.INTERNET)) { permissionCallback.onPermissionExplanationRequired(true, Manifest.permission.INTERNET); } else { ActivityCompat.requestPermissions( activity, new String[] {Manifest.permission.INTERNET}, INTERNET_PERMISSION); } }
/** Request permission to write to storage. */ private void requestWritePermissions() { int REQUEST_WRITE_STORAGE = 112; boolean hasPermission = (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED); if (!hasPermission) { ActivityCompat.requestPermissions( this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_STORAGE); } }
public static void Storage() { if (ContextCompat.checkSelfPermission( UIUtils.getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( UIUtils.getActivity(), new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, Constant.WRITE_EXTERNAL_STORAGE_REQUEST_CODE); } }
private void requestPermission() { // Permission has not been granted and must be requested. if (ActivityCompat.shouldShowRequestPermissionRationale( mActivity, Manifest.permission.ACCESS_FINE_LOCATION)) { ActivityCompat.requestPermissions( mActivity, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST); } else { if (mOnPermissionListener != null) { mOnPermissionListener.OnPermissionChanged(false); } // Request the permission. The result will be received in onRequestPermissionResult(). ActivityCompat.requestPermissions( mActivity, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST); } }
/** * Requests the fine location permission. If a rationale with an additional explanation should be * shown to the user, displays a dialog that triggers the request. */ public static void requestPermission( AppCompatActivity activity, int requestId, String permission, boolean finishActivity) { if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) { // Display a dialog with rationale. RationaleDialog.newInstance(requestId, finishActivity) .show(activity.getSupportFragmentManager(), "dialog"); } else { // Location permission has not been granted yet, request it. ActivityCompat.requestPermissions(activity, new String[] {permission}, requestId); } }
public void onMainShapeTouch(View v) { if (getState() != State.IDLE) return; if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) { ActivityCompat.requestPermissions( this, new String[] {Manifest.permission.CAMERA}, PERMISSION_REQUEST_CAMERA); } else { startQRScanner(getString(R.string.scan_qr)); } }
// Checks if the user has given location permission and asks for it if he hasn't private void checkForPermission() { if (ContextCompat.checkSelfPermission( MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( MainActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST); } else { startService(new Intent(this, LocationService.class)); } }
@Override public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) { lawg.d("Has camera permission? " + hasPermission(Manifest.permission.CAMERA)); if (hasPermission(Manifest.permission.CAMERA)) { startCamera2(width, height); } else { ActivityCompat.requestPermissions( CameraActivity.this, new String[] {Manifest.permission.CAMERA}, CAMERA_PERMISSIONS_REQUEST); } }
private void requestPermissionForCameraAndMicrophone() { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale( this, Manifest.permission.RECORD_AUDIO)) { Toast.makeText(this, R.string.permissions_needed, Toast.LENGTH_LONG).show(); } else { ActivityCompat.requestPermissions( this, new String[] {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}, CAMERA_MIC_PERMISSION_REQUEST_CODE); } }
public void requestExternalStoragePermission() { if (ActivityCompat.shouldShowRequestPermissionRationale( activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { permissionCallback.onPermissionExplanationRequired( true, Manifest.permission.WRITE_EXTERNAL_STORAGE); } else { ActivityCompat.requestPermissions( activity, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION); } }
public void requestExternalStoragePermission( AppCompatActivity appCompatActivity, PermissionCallback callback, boolean requestFromDialog) { if (ActivityCompat.shouldShowRequestPermissionRationale( appCompatActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) && !requestFromDialog) { callback.onPermissionExplanationRequired(true, Manifest.permission.WRITE_EXTERNAL_STORAGE); } else { ActivityCompat.requestPermissions( appCompatActivity, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION); } }