Java Code Examples for android.content.pm.PackageManager#PERMISSION_GRANTED

The following examples show how to use android.content.pm.PackageManager#PERMISSION_GRANTED . 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: SplashActivity.java    From Bailan with Apache License 2.0 6 votes vote down vote up
/**
 * 申请权限结果回调
 * @param requestCode 请求码
 * @param permissions 申请权限的数组
 * @param grantResults 申请权限成功与否的结果
 */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode){
        case 1:
            if (grantResults.length > 0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                //申请成功
                ToastUtils.showShortToast("授权SD卡权限成功");
            }else {
                //申请失败
                ToastUtils.showShortToast("授权SD卡权限失败 可能会影响应用的使用");
            }
            break;
    }

}
 
Example 2
Source File: FaceTrackerActivity.java    From android-vision with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the UI and initiates the creation of a face detector.
 */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    mPreview = (CameraSourcePreview) findViewById(R.id.preview);
    mGraphicOverlay = (GraphicOverlay) findViewById(R.id.faceOverlay);

    // 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();
    } else {
        requestCameraPermission();
    }
}
 
Example 3
Source File: MainActivity.java    From dialogflow-java-client with Apache License 2.0 6 votes vote down vote up
protected void checkAudioRecordPermission() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.RECORD_AUDIO)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.RECORD_AUDIO)) {

            // 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.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.RECORD_AUDIO},
                    REQUEST_AUDIO_PERMISSIONS_ID);

        }
    }
}
 
Example 4
Source File: FingerprintAuth.java    From keemob with MIT License 6 votes vote down vote up
@Override
public void onRequestPermissionResult(int requestCode, String[] permissions,
                                      int[] grantResults) throws JSONException {
    super.onRequestPermissionResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case PERMISSIONS_REQUEST_FINGERPRINT: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                sendAvailabilityResult();
            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Log.e(TAG, "Fingerprint permission denied.");
                setPluginResultError(PluginError.FINGERPRINT_PERMISSION_DENIED.name());
            }
            return;
        }
    }
}
 
Example 5
Source File: AtlasFragment.java    From memoir with Apache License 2.0 6 votes vote down vote up
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setOnMarkerClickListener(this);
    refreshMarkers();

    // Request for FINE_LOCATION
    if (Build.VERSION.SDK_INT >= 23) {
        if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION }, PERMISSION_ACCESS_FINE_LOCATION);
        } else {
            // Request for COARSE LOCATION
            if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_ACCESS_COARSE_LOCATION);
            } else {
                // Request granted, get user's location
                mMap.setMyLocationEnabled(true);
            }
        }
    }
}
 
Example 6
Source File: DocumentsContractApi19.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
public static boolean canWrite(Context context, Uri self) {
    // Ignore if grant doesn't allow write
    if (context.checkCallingOrSelfUriPermission(self, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            != PackageManager.PERMISSION_GRANTED) {
        return false;
    }

    final String type = getRawType(context, self);
    final int flags = queryForInt(context, self, DocumentsContract.Document.COLUMN_FLAGS, 0);

    // Ignore documents without MIME
    if (TextUtils.isEmpty(type)) {
        return false;
    }

    // Deletable documents considered writable
    if ((flags & DocumentsContract.Document.FLAG_SUPPORTS_DELETE) != 0) {
        return true;
    }

    if (DocumentsContract.Document.MIME_TYPE_DIR.equals(type)
            && (flags & DocumentsContract.Document.FLAG_DIR_SUPPORTS_CREATE) != 0) {
        // Directories that allow create considered writable
        return true;
    } else if (!TextUtils.isEmpty(type)
            && (flags & DocumentsContract.Document.FLAG_SUPPORTS_WRITE) != 0) {
        // Writable normal files considered writable
        return true;
    }

    return false;
}
 
Example 7
Source File: MainActivity.java    From here-android-sdk-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
    switch (requestCode) {
        case REQUEST_CODE_ASK_PERMISSIONS: {
            for (int index = 0; index < permissions.length; index++) {
                if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {

                    /*
                     * If the user turned down the permission request in the past and chose the
                     * Don't ask again option in the permission request system dialog.
                     */
                    if (!ActivityCompat
                            .shouldShowRequestPermissionRationale(this, permissions[index])) {
                        Toast.makeText(this, "Required permission " + permissions[index]
                                               + " not granted. "
                                               + "Please go to settings and turn on for sample app",
                                       Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(this, "Required permission " + permissions[index]
                                + " not granted", Toast.LENGTH_LONG).show();
                    }
                }
            }

            setupMapView();
            break;
        }
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
 
Example 8
Source File: RuntimePermissionUtil.java    From sensey with Apache License 2.0 5 votes vote down vote up
public static void onRequestPermissionsResult(int[] grantResults,
        RPResultListener rpResultListener) {
    if (grantResults.length > 0) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_GRANTED) {
                rpResultListener.onPermissionGranted();
            } else {
                rpResultListener.onPermissionDenied();
            }
        }
    }
}
 
Example 9
Source File: Utils.java    From mlkit-material-android with Apache License 2.0 5 votes vote down vote up
static void requestRuntimePermissions(Activity activity) {
  List<String> allNeededPermissions = new ArrayList<>();
  for (String permission : getRequiredPermissions(activity)) {
    if (checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
      allNeededPermissions.add(permission);
    }
  }

  if (!allNeededPermissions.isEmpty()) {
    ActivityCompat.requestPermissions(
        activity, allNeededPermissions.toArray(new String[0]), /* requestCode= */ 0);
  }
}
 
Example 10
Source File: BarcodeCaptureActivity.java    From android-vision with Apache License 2.0 5 votes vote down vote up
/**
 * Callback for the result from requesting permissions. This method
 * is invoked for every call on {@link #requestPermissions(String[], int)}.
 * <p>
 * <strong>Note:</strong> It is possible that the permissions request interaction
 * with the user is interrupted. In this case you will receive empty permissions
 * and results arrays which should be treated as a cancellation.
 * </p>
 *
 * @param requestCode  The request code passed in {@link #requestPermissions(String[], int)}.
 * @param permissions  The requested permissions. Never null.
 * @param grantResults The grant results for the corresponding permissions
 *                     which is either {@link PackageManager#PERMISSION_GRANTED}
 *                     or {@link PackageManager#PERMISSION_DENIED}. Never null.
 * @see #requestPermissions(String[], int)
 */
@Override
public void onRequestPermissionsResult(int requestCode,
                                       @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    if (requestCode != RC_HANDLE_CAMERA_PERM) {
        Log.d(TAG, "Got unexpected permission result: " + requestCode);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        return;
    }

    if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        Log.d(TAG, "Camera permission granted - initialize the camera source");
        // we have permission, so create the camerasource
        boolean autoFocus = getIntent().getBooleanExtra(AutoFocus,false);
        boolean useFlash = getIntent().getBooleanExtra(UseFlash, false);
        createCameraSource(autoFocus, useFlash);
        return;
    }

    Log.e(TAG, "Permission not granted: results len = " + grantResults.length +
            " Result code = " + (grantResults.length > 0 ? grantResults[0] : "(empty)"));

    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            finish();
        }
    };

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Multitracker sample")
            .setMessage(R.string.no_camera_permission)
            .setPositiveButton(R.string.ok, listener)
            .show();
}
 
Example 11
Source File: AttachmentViewerActivity.java    From mage-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
	super.onRequestPermissionsResult(requestCode, permissions, grantResults);

	switch (requestCode) {
		case PERMISSIONS_REQUEST_STORAGE: {
			if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
				new DownloadFileAsync().execute(attachment);
			} else {
				if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
					new AlertDialog.Builder(this)
							.setTitle(R.string.storage_access_title)
							.setMessage(R.string.storage_access_message)
							.setPositiveButton(R.string.settings, new Dialog.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
									intent.setData(Uri.fromParts("package", getApplicationContext().getPackageName(), null));
									startActivity(intent);
								}
							})
							.setNegativeButton(android.R.string.cancel, null)
							.show();
				}
			}

			break;
		}
	}
}
 
Example 12
Source File: Connection.java    From PS4-Payload-Sender-Android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_connection);
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)) {
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_FILES);
        }
    } else {
    }

    ConnectBtn = (Button) findViewById(R.id.ConnectBtn);
    SendBtn = (Button) findViewById(R.id.SendPayloadBtn);
    BrowseBtn = (Button) findViewById(R.id.BrowsePayloadBtn);
    Injecting = (TextView) findViewById(R.id.InjectingLbl);

    BrowseBtn.setEnabled(false);
    SendBtn.setEnabled(false);

    Injecting.setVisibility(TextView.INVISIBLE);

}
 
Example 13
Source File: ContactOverviewFragment.java    From natrium-android-wallet with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void showExportDialog() {
    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        showExport = true;
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_STORAGE_PERMISSION);
        return;
    }
    List<Contact> contacts = realm.where(Contact.class).findAll();
    if (contacts.size() == 0) {
        UIUtil.showToast(getString(R.string.contact_export_none), getContext());
        return;
    }
    JSONArray contactJson = new JSONArray();
    for (Contact c : contacts) {
        contactJson.put(c.getJson());
    }
    // Save file
    try {
        DateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss", Locale.US);
        String fileName = String.format("%s_contacts_%s.json", getString(R.string.app_name), dateFormat.format(new Date())).toLowerCase();
        FileWriter out = new FileWriter(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName));
        out.write(contactJson.toString());
        out.close();
        UIUtil.showToast(getString(R.string.contact_export_success, new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName).getAbsoluteFile()), getContext());
    } catch (IOException e) {
        Timber.e(e);
        UIUtil.showToast(getString(R.string.contact_export_error), getContext());
    }
}
 
Example 14
Source File: MainActivity.java    From googlecalendar with Apache License 2.0 5 votes vote down vote up
@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==200&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
            LocalDate mintime=new LocalDate().minusYears(10);
            LocalDate maxtime=new LocalDate().plusYears(10);
            HashMap<LocalDate,String[]> eventlist=Utility.readCalendarEvent(this,mintime,maxtime);
            calendarView.init(eventlist,mintime.minusYears(10),maxtime.plusYears(10));
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    lastdate=new LocalDate();
                    calendarView.setCurrentmonth(new LocalDate());
                    calendarView.adjustheight();
//                    LinearLayoutManager linearLayoutManager= (LinearLayoutManager) mNestedView.getLayoutManager();
//                    if (indextrack.containsKey(new LocalDate())){
//                        smoothScroller.setTargetPosition(indextrack.get(new LocalDate()));
//                        linearLayoutManager.scrollToPositionWithOffset(indextrack.get(new LocalDate()),0);
//                    }
//                    else {
//                        for (int i=0;i<eventalllist.size();i++){
//                            if (eventalllist.get(i).getLocalDate().getMonthOfYear()==new LocalDate().getMonthOfYear()&&eventalllist.get(i).getLocalDate().getYear()==new LocalDate().getYear()){
//                                linearLayoutManager.scrollToPositionWithOffset(i,0);
//                                break;
//                            }
//                        }
//                    }
                }
            },10);
        }
    }
 
Example 15
Source File: MyLocationDemoActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Enables the My Location layer if the fine location permission has been granted.
 */
private void enableMyLocation() {
    // [START maps_check_location_permission]
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        if (map != null) {
            map.setMyLocationEnabled(true);
        }
    } else {
        // Permission to access the location is missing. Show rationale and request permission
        PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
            Manifest.permission.ACCESS_FINE_LOCATION, true);
    }
    // [END maps_check_location_permission]
}
 
Example 16
Source File: ScannerService.java    From com.ruuvi.station with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void updateLocation() {
    FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getApplicationContext());
    if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                tagLocation = location;
            }
        });
    }
}
 
Example 17
Source File: TakePhotoActivity.java    From LQRWeChat with MIT License 5 votes vote down vote up
@Override
public void init() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
            || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
            || ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED)
        PermissionGen.with(this)
                .addRequestCode(100)
                .permissions(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO)
                .request();
}
 
Example 18
Source File: SupportPermissionActionImpl.java    From PermissionsSample with Apache License 2.0 4 votes vote down vote up
@Override
public boolean hasSelfPermission(String permission) {
    return ContextCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_GRANTED;
}
 
Example 19
Source File: PermissionUtils.java    From YCUpdateApp with Apache License 2.0 4 votes vote down vote up
private static boolean isGranted(final String permission) {
    return Build.VERSION.SDK_INT < Build.VERSION_CODES.M
            || PackageManager.PERMISSION_GRANTED
            == ContextCompat.checkSelfPermission(sApplication, permission);
}
 
Example 20
Source File: PermissionUtils.java    From PermissionUtils with MIT License 2 votes vote down vote up
/**
 * @param context    current context
 * @param permission permission to check
 * @return if permission is granted return true
 */
public static boolean isGranted(Context context, PermissionEnum permission) {
    return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || ContextCompat.checkSelfPermission(context, permission.toString()) == PackageManager.PERMISSION_GRANTED;
}