【发布时间】:2015-12-13 10:02:54
【问题描述】:
【问题讨论】:
标签: android android-6.0-marshmallow
【问题讨论】:
标签: android android-6.0-marshmallow
Use ContextCompat.checkSelfPermission()、ActivityCompat.requestPermissions() 和 ActivityCompat.shouldShowPermissionRequestRationale(),来自 support-v4 库(v23 或更高版本)。这些是向后兼容的;如果您在旧版本的 Android 上运行,它们将“做正确的事”(例如,为 ContextCompat.checkSelfPermission() 返回 PackageManager.PERMISSION_GRANTED)。
【讨论】:
targetSdkVersion 需要为 23 或更高。
ActivityCompat.checkSelfPermission 不会返回授予的权限。
您可以查看构建版本if(Build.Version.SDK_INT >= Build.VERSION_CODES.MARSHMALLOW)。然后在那里处理棉花糖权限,否则处理其他版本。
【讨论】:
在获得检查权限之前检查您的 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
你必须调用方法:)
【讨论】:
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;
}
【讨论】: