support-v4
库(v23或更高版本)中的 ContextCompat.checkSelfPermission()
、ActivityCompat.requestPermissions()
和ActivityCompat.shouldShowPermissionRequestRationale()
。这些方法是向后兼容的;如果您运行在旧版 Android 上,它们会“做正确的事情”(例如,对于ContextCompat.checkSelfPermission()
, 会返回 PackageManager.PERMISSION_GRANTED
)。在获取检查权限之前,请检查您的Android版本:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(@NonNull String[] permissions, int requestCode)
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
}else{
//Do Your Stuff
}
如果您不想按照这里描述的方式使用AppCompatActivity,可以按照以下步骤操作:https://codemammoth.blogspot.gr/2016/06/how-to-invoke-checkselfpermission.html
您需要调用方法:)
if(Build.Version.SDK_INT >= Build.VERSION_CODES.MARSHMALLOW)
。然后在其中处理棉花糖权限,在其他版本中处理其他事项。checkSelfPermission在sdk 23以上可用。
我们可以使用包管理器检查权限是否可用。
public static Boolean checkpermissions(Activity activity) {
PackageManager mPackageManager = activity.getPackageManager();
int hasPermStorage = mPackageManager.checkPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, activity.getPackageName());
if (hasPermStorage != PackageManager.PERMISSION_GRANTED) {
// do stuff
//Toast.makeText(getApplicationContext(), "No permission", Toast.LENGTH_LONG).show();
return false;
} else if (hasPermStorage == PackageManager.PERMISSION_GRANTED) {
// do stuff
//Toast.makeText(getApplicationContext(), "Has permission", Toast.LENGTH_LONG).show();
return true;
}else
return false;
}
targetSdkVersion
需要是23或更高。 - CommonsWareActivityCompat.checkSelfPermission
不会返回已授权的权限。 - Eir