1.問題描述
Android調用相機拍照保存,然后讀取保存好的照片,在讀取照片時出現異常(該異常是因為沒有SD卡的讀取權限所致):
11-08 11:07:46.421 8539-8539/com.choosepictest D/CROP_PHOTO: /storage/emulated/0/output_image.jpg: open failed: EACCES (Permission denied)
下面是Java代碼:
public void btnTakePhoto_onClick(View view)
{
picture = (ImageView)findViewById(R.id.ivPicture);
// 創建File對象,用於存儲拍照后的圖片
File outputImage = new File(Environment.getExternalStorageDirectory(),"output_image.jpg");
try
{
if(outputImage.exists())
{
outputImage.delete();
}
outputImage.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
imageUri = Uri.fromFile(outputImage);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(intent,TAKE_PHOTO);
}
@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data)
{
switch (requestCode)
{
case TAKE_PHOTO:
if(resultCode == RESULT_OK)
{
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(imageUri,"image/*");
intent.putExtra("scale",true);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(intent,CROP_PHOTO);
}
break;
case CROP_PHOTO:
if(resultCode == RESULT_OK)
{
try
{
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bitmap);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
Log.d("CROP_PHOTO",e.getMessage());
}
}
break;
}
}
因為是權限問題,所以在AndroidManifest.xml中添加了相應權限,但是問題沒有解決,下面是AndroidManifest.xml代碼:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.choosepictest">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
2.解決方法
在往上查找了一些解決辦法,基本上都是添加權限,但是權限我已經添加,問題還是沒有解決,暫時沒有找到解決辦法。下面是網上的解決方法:
http://blog.csdn.net/zxkevin1989/article/details/7464550/
http://stackoverflow.com/questions/8854359/exception-open-failed-eacces-permission-denied-on-android
http://stackoverflow.com/questions/26208751/filenotfoundexception-storage-emulated-0-pictures-pic-jpg-open-failed-eacces
注:上述解決辦法都是正確的,是我的手機自動禁用了App的存儲權限,開啟權限后,問題解決。