BitmapFactory.decodeFile在Android 4.4 KitKat上返回异常

时间:2013-12-21 11:14:44

标签: android android-bitmap

我想使用以下代码显示图像:

protected void onActivityResult(int requestCode, int resultCode, 
       Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

    switch(requestCode) { 
    case SELECT_PHOTO:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(
                               selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();
            Log.wtf("M3K", "Above decode");
            Bitmap logoBMP = BitmapFactory.decodeFile(filePath);
            Log.wtf("M3K", "Below decode");

            //Display image on layout
            Log.wtf("M3K", "Above display");
            logo.setImageBitmap(logoBMP);
            Log.wtf("M3K", "Below display");
        }
    }
}

问题出在Bitmap logoBMP = BitmapFactory.decodeFile(filePath); Android 4.4(在我的Nexus 7上测试),它将返回一个未找到文件的异常,原因是 EACCES(权限被拒绝)。这在运行4.2的华硕Transformer Infinity上完美运行,并且在我的运行4.3的Nexus 7上完美运行。有谁知道KitKat兼容性需要改变什么?

注意:我通过以下代码获取图像URI:

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);

1 个答案:

答案 0 :(得分:5)

您可以尝试将以下内容放入清单文件中:

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />