我想从图库中获取图片,但我不明白。我刚收到错误:
无法解码流:java.io.FileNotFoundException:/storage/emulated/0/DCIM/Screenshots/Screenshot_20160715-233221.png:open failed:EACCES(Permission denied)
我有这段代码:
Intent i = new Intent(PostCreateActivity.this, MainActivity.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
而且:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
try{
if(requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data){
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
}catch(Exception e){
Toast.makeText(this, "Something went wrong!", Toast.LENGTH_SHORT).show();
}
}
和
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
但我一直收到这个错误。我该怎么办?
答案 0 :(得分:1)
如果您使用的是Android 6.0或更高版本,则必须在运行时请求权限:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//......
//Check and ask for permissions in version Android API 23 and above.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkPermissions();
}
//.....
}
private void checkPermissions(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED||
ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},
1052);
}
}
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1052: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED {
// permission was granted.
} else {
// Permission denied - Show a message to inform the user that this app only works
// with these permissions granted
}
return;
}
}
}