在项目中保存网络图片到手机本地时,保存图片失败,出现这种原因的话有可能是下面原因:
Android 6.0 中,有些权限属于 Protected Permission,这类权限只在 AndroidManifest.xml中声明是无法真正获取到的,还需要再代码中动态获取,使权限许可弹出对话框,用户点击“允许”后,方可真正获得此权限
1.清单文件中没有对应的权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
2.如果不写以上代码,还可以用另外一种简单简单粗暴的方式:直接在6.0的设置里面找到应用,选中你的APP->权限->打开存储空间权限
3.添加动态权限:
/**
* 动态获取权限,Android 6.0 新特性,一些保护权限,除了要在AndroidManifest中声明权限,还要使用如下代码动态获取
*/
if (Build.VERSION.SDK_INT >= 23) {
int REQUEST_CODE_CONTACT = 101;
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
//验证是否许可权限
for (String str : permissions) {
if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
//申请权限
this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
return;
}
}
}
或
// 6.0及以上的系统需要在运行时申请CAMERA RECORD_AUDIO权限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(PhotoDetailActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(PhotoDetailActivity.this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(PhotoDetailActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(PhotoDetailActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(PhotoDetailActivity.this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(PhotoDetailActivity.this, new String[]{
Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO
, Manifest.permission.WRITE_EXTERNAL_STORAGE
, Manifest.permission.READ_EXTERNAL_STORAGE
, Manifest.permission.READ_SMS}, 101);
}
}