Java android Java.io.FileNotFoundException: No content provider: /storage/emulated/0/Android/data Java安卓Java.io.FileNotFoundException:无内容提供程序:/storage/emulated/0/Android/data

6

我希望能够拍照并在imageView中显示这张照片,但是在api 23和24上无法正常工作。我尝试添加了一个文件提供程序,以下是我的做法。

我的活动:

public class TestActivity extends AppCompatActivity {

    ImageView iv;
    private File photoFile;
    private String mCurrentPhotoPath;
    private static final String TAG = "PHOTO";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        iv = (ImageView) findViewById(R.id.iv);

        photo();


    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            if (mCurrentPhotoPath != null) {
                File file = new File(mCurrentPhotoPath);
                if(file.exists())
                    Log.e(TAG , "photo jest");
                try {
                    Bitmap mImageBitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), Uri.parse(mCurrentPhotoPath));
                    iv.setImageBitmap(mImageBitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(TestActivity.this, "Nie udało się zapisać zdjęcia ", Toast.LENGTH_LONG).show();
            }

        }
    }
    void photo() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (cameraIntent.resolveActivity(getApplicationContext().getPackageManager()) != null) {
                // Create the File where the photo should go
                photoFile = null;
                try {
                    photoFile = createImageFile();
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Log.i(TAG, "IOException");
                }
                // Continue only if the File was successfully created
                if (photoFile != null) {
                    Uri photoURI = null;
                    try {
                        photoURI = FileProvider.getUriForFile(getApplicationContext(),
                                BuildConfig.APPLICATION_ID + ".provider",
                                createImageFile());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
//                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

                    startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
                }
            }
        }
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }
}

在清单文件中,我添加了一个文件提供者:

  <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="eltegps.pl.mobileterminal.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>

这是我的文件提供程序:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/eltegps.pl.mobileterminal/files/Pictures" />
</paths>

当我在logcat上拍照时,我看到了这个:
08-23 08:47:01.298 25695-25695/eltegps.pl.mobileterminal W/System.err: java.io.FileNotFoundException: No content provider: /storage/emulated/0/Android/data/eltegps.pl.mobileterminal/files/Pictures/JPEG_20170823_084656_-159214243.jpg
08-23 08:47:01.298 25695-25695/eltegps.pl.mobileterminal W/System.err:     at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1141)
08-23 08:47:01.298 25695-25695/eltegps.pl.mobileterminal W/System.err:     at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:991)
08-23 08:47:01.298 25695-25695/eltegps.pl.mobileterminal W/System.err:     at android.content.ContentResolver.openInputStream(ContentResolver.java:711)
08-23 08:47:01.298 25695-25695/eltegps.pl.mobileterminal W/System.err:     at android.provider.MediaStore$Images$Media.getBitmap(MediaStore.java:890)
08-23 08:47:01.298 25695-25695/eltegps.pl.mobileterminal W/System.err:     at eltegps.pl.mobileterminal.Activity.TestActivity.onActivityResult(TestActivity.java:54)
08-23 08:47:01.298 25695-25695/eltegps.pl.mobileterminal W/System.err:     at android.app.Activity.dispatchActivityResult(Activity.java:7137)

我这里出现了一个FileNotFoundException异常

 Bitmap mImageBitmap 

    =MediaStore.Images.Media.getBitmap(getApplicationContext().



 getContentResolver(), Uri.parse(mCurrentPhotoPath));

在第一个活动中,我检查权限;

  private boolean checkAndRequestPermissions() {

        int permissionSendMessage = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
        int cameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        listPermissionsNeeded = new ArrayList<>();
        if (locationPermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (cameraPermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.CAMERA);
        }

        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
            return false;
        }
        return true;
    }

private void logIn(){
    startActivity(new Intent(MainActivity.this, TestActivity.class));
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    if (requestCode == REQUEST_ID_MULTIPLE_PERMISSIONS && grantResults.length == listPermissionsNeeded.size()) {
        boolean allGranted = true;
        for (int grantedResult : grantResults) {
            if (grantedResult != PackageManager.PERMISSION_GRANTED) {
                allGranted = false;
            }
        }
        if (allGranted) {
            logIn();
        }
    }
}

1
请使用运行时权限代码进行验证,然后重试。 - Android Geek
在 Android 23 及以上版本中,读写外部存储需要运行时权限。您可以参考以下链接:https://dev59.com/J1wX5IYBdhLWcg3w-Thv - Jay Rathod
2个回答

26

我也遇到了这个问题,也许已经晚了,但我希望它能帮助到某个人。我的问题得到了解决。

问题出在这一行代码:
Bitmap mImageBitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), Uri.parse(mCurrentPhotoPath));

尝试将 Uri.parse(mCurrentPhotoPath) 改为 Uri.fromFile(new File(mCurrentPhotoPath))

因为 Uri.fromFile(new File(mCurrentPhotoPath)) 会生成类似于 file:///Android/data/eltegps.pl.mobileterminal/files/Pictures/namefile.mp4 的内容,正如该方法参数所需的那样。


我的朋友,你真的帮了我大忙。正如你所提到的那样,我的代码是Uri.parse(currentPhotoPath)。 - Samir

2

在存储和读取位图之前,您需要请求运行时权限以进行存储和读取存储空间。


我该如何请求这个? - Krzysztof Pokrywka
请点击以下链接查看与Marshmallow M运行时权限相关的Android编程内容:https://www.androidhive.info/2016/11/android-working-marshmallow-m-runtime-permissions/ - Nikhil Jadhav
我把我做的事情和如何检查权限放了进去,但它不起作用。 - Krzysztof Pokrywka
你只为读取存储添加了权限,但没有为写入存储添加权限。 - Nikhil Jadhav
在保存位图和从内容提供程序获取位图时,请确保路径相同:Android/data/eltegps.pl.mobileterminal/files/Pictures - Nikhil Jadhav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接