1.在AndroidManifest.xml中配置请求权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2.在onCreate(Bundle savedInstanceState)方法中请求权限
//授权请求
if (Build.VERSION.SDK_INT >= 24) {
System.out.println("版本正确");
checkPermission();
}else {
System.out.println("版本过低");
}
权限检测实现代码
private static final int REQUEST_CODE = 1;
private static String[] PERMISSIONS_STORAGE = {
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.WRITE_EXTERNAL_STORAGE"};
//授权检测
private void checkPermission() {
//权限是否已经赋予
if (m_activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//未赋予权限,申请权限
if (m_activity.shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//选择不开启权限的时候,提示用户
Toast.makeText(m_activity.getApplicationContext() , "请开通相关权限,否则无法正常使用本应用!", Toast.LENGTH_SHORT).show();
}
//申请权限
m_activity.requestPermissions( PERMISSIONS_STORAGE, REQUEST_CODE);
} else {
//权限已赋予
Toast.makeText(m_activity.getApplicationContext(), "已授权成功!", Toast.LENGTH_SHORT).show();
}
}
权限请求结果代码
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
//权限的申请结果返回
case REQUEST_CODE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//已授权
Toast.makeText(m_activity.getApplicationContext(), "授权成功!", Toast.LENGTH_SHORT).show();
} else {
//未授权
Toast.makeText(m_activity.getApplicationContext(), "授权被拒绝!", Toast.LENGTH_SHORT).show();
}
}
}
}