如何在不抛出SecurityException的情况下在运行时检查权限?
我devise了一个函数,可以从SD中获取/设置一个资源,如果没有从sd中find资源,则从资产中获取资源,如果可能,将资产写回SD
这个函数可以通过方法调用来检查SD是否被挂载并可访问。
boolean bSDisAvalaible = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
我devise的function可以使用从一个应用程序(项目)到另一个(有或没有android.permission.WRITE_EXTERNAL_STORAGE)
然后我想检查当前的应用程序是否有这个特殊的权限,而不玩SecurityException。
它是否存在一个“很好”的方式在运行时查询当前定义的权限?
您可以使用Context.checkCallingorSelfPermission()
函数。 这里是一个例子:
private boolean checkWriteExternalPermission() { String permission = "android.permission.WRITE_EXTERNAL_STORAGE"; int res = getContext().checkCallingOrSelfPermission(permission); return (res == PackageManager.PERMISSION_GRANTED); }
这也是另一个解决scheme
PackageManager pm = context.getPackageManager(); int hasPerm = pm.checkPermission( android.Manifest.permission.WRITE_EXTERNAL_STORAGE, context.getPackageName()); if (hasPerm != PackageManager.PERMISSION_GRANTED) { // do stuff }
你也可以使用这个:
private boolean doesUserHavePermission() { int result = context.checkCallingOrSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE); return result == PackageManager.PERMISSION_GRANTED; }
像Google 文档一样:
// Assume thisActivity is the current activity int permissionCheck = ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
如果有人需要,分享我的方法:
/** Determines if the context calling has the required permission * @param context - the IPC context * @param permissions - The permissions to check * @return true if the IPC has the granted permission */ public static boolean hasPermission(Context context, String permission) { int res = context.checkCallingOrSelfPermission(permission); Log.v(TAG, "permission: " + permission + " = \t\t" + (res == PackageManager.PERMISSION_GRANTED ? "GRANTED" : "DENIED")); return res == PackageManager.PERMISSION_GRANTED; } /** Determines if the context calling has the required permissions * @param context - the IPC context * @param permissions - The permissions to check * @return true if the IPC has the granted permission */ public static boolean hasPermissions(Context context, String... permissions) { boolean hasAllPermissions = true; for(String permission : permissions) { //you can return false instead of assigning, but by assigning you can log all permission values if (! hasPermission(context, permission)) {hasAllPermissions = false; } } return hasAllPermissions; }
并称之为:
boolean hasAndroidPermissions = SystemUtils.hasPermissions(mContext, new String[] { android.Manifest.permission.ACCESS_WIFI_STATE, android.Manifest.permission.READ_PHONE_STATE, android.Manifest.permission.ACCESS_NETWORK_STATE, android.Manifest.permission.INTERNET, });
您应该按照以下方式检查权限(如此处所述的Android权限 ):
int result = ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_PHONE_STATE);
那么,比较你的结果:
result == PackageManager.PERMISSION_DENIED
要么:
result == PackageManager.PERMISSION_GRANTED
对我来说工作正常的代码是:
final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 102; if ((ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) { requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE); } else { // user already provided permission // perform function for what you want to achieve } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { boolean canUseExternalStorage = false; switch (requestCode) { case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { canUseExternalStorage = true; } if (!canUseExternalStorage) { Toast.makeText(getActivity(), "Cannot use this feature without requested permission", Toast.LENGTH_SHORT).show(); } else { // user now provided permission // perform function for what you want to achieve } } } }
启用GPS位置Android Studio
- 在AndroidManifest.Xml中添加权限条目
-
MapsActivity.java
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; private Context context; private static final int PERMISSION_REQUEST_CODE = 1; Activity activity; /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client; @Override protected void onCreate(Bundle savedInstanceState) { context = getApplicationContext(); activity = this; super.onCreate(savedInstanceState); requestPermission(); checkPermission(); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; LatLng location = new LatLng(0, 0); mMap.addMarker(new MarkerOptions().position(location).title("Marker in Bangalore")); mMap.moveCamera(CameraUpdateFactory.newLatLng(location)); mMap.setMyLocationEnabled(true); } private void requestPermission() { if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION)) { Toast.makeText(context, "GPS permission allows us to access location data. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show(); } else { ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE); } } private boolean checkPermission() { int result = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION); if (result == PackageManager.PERMISSION_GRANTED) { return true; } else { return false; } }