android.content.pm.PackageManager#PERMISSION_GRANTED源码实例Demo

下面列出了android.content.pm.PackageManager#PERMISSION_GRANTED 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: keemob   文件: FingerprintAuth.java
@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;
        }
    }
}
 
源代码2 项目: Bailan   文件: SplashActivity.java
/**
 * 申请权限结果回调
 * @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;
    }

}
 
源代码3 项目: memoir   文件: AtlasFragment.java
@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);
            }
        }
    }
}
 
源代码4 项目: dialogflow-java-client   文件: MainActivity.java
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);

        }
    }
}
 
源代码5 项目: android-vision   文件: FaceTrackerActivity.java
/**
 * 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();
    }
}
 
源代码6 项目: LQRWeChat   文件: TakePhotoActivity.java
@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();
}
 
源代码7 项目: com.ruuvi.station   文件: ScannerService.java
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;
            }
        });
    }
}
 
源代码8 项目: android-samples   文件: MyLocationDemoActivity.java
/**
 * 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]
}
 
源代码9 项目: googlecalendar   文件: MainActivity.java
@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);
        }
    }
 
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());
    }
}
 
源代码11 项目: PS4-Payload-Sender-Android   文件: Connection.java
@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);

}
 
源代码12 项目: FireFiles   文件: DocumentsContractApi19.java
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;
}
 
源代码13 项目: mage-android   文件: AttachmentViewerActivity.java
@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;
		}
	}
}
 
源代码14 项目: android-vision   文件: BarcodeCaptureActivity.java
/**
 * 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();
}
 
源代码15 项目: mlkit-material-android   文件: Utils.java
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);
  }
}
 
源代码16 项目: sensey   文件: RuntimePermissionUtil.java
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();
            }
        }
    }
}
 
源代码17 项目: here-android-sdk-examples   文件: MainActivity.java
@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);
    }
}
 
源代码18 项目: YCUpdateApp   文件: PermissionUtils.java
private static boolean isGranted(final String permission) {
    return Build.VERSION.SDK_INT < Build.VERSION_CODES.M
            || PackageManager.PERMISSION_GRANTED
            == ContextCompat.checkSelfPermission(sApplication, permission);
}
 
@Override
public boolean hasSelfPermission(String permission) {
    return ContextCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_GRANTED;
}
 
源代码20 项目: PermissionUtils   文件: PermissionUtils.java
/**
 * @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;
}