如何使用Media Store API将媒体文件保存在应用程序特定的文件夹中-Scoped Storage Android

问题描述

我正在尝试使用适用于Android 10及更高版本的范围存储将从相机拍摄的图像保存在应用程序特定的文件夹中。 我知道如何使用File API来做到这一点,但我正在寻找通过Media store API来做到这一点。

这是问题所在,使用以下代码将图像保存在“内部存储”>“图片”中,但不将其保存在应用程序特定的文件夹中。因此,如果我卸载该应用程序,则该应用程序保存的图像仍保留在内存中。如果用户从手机中删除该应用程序,我希望它们被自动删除

让我知道我做错了还是缺少什​​么。

    private void dispatchTakePictureIntent() throws IOException {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            if (!checkIfVersionCodeQAndAbove()) {
                try {
                    photoFile = createImageFile();
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    return;
                }
                // Continue only if the File was successfully created
                if (photoFile != null) {
                    Uri photoURI = FileProvider.getUriForFile(getActivity().getApplicationContext(),getActivity().getPackageName() + ".provider",createImageFile());
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);
                }
            }
            if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                startActivityForResult(takePictureIntent,TAKE_PICTURE);
            }
        }
    }


private void storeImageUsingMediaApi(Intent data) {
        if (getActivity()!=null) {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
            String imageFileName = "JPEG_" + timeStamp + "_";

            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.Images.Media.TITLE,imageFileName + ".jpg");
            contentValues.put(MediaStore.Images.Media.DESCRIPTION,"profile_image");
            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH,Environment.DIRECTORY_PICTURES  + File.separator + "MyApp");

            ContentResolver resolver = getActivity().getContentResolver();

            OutputStream stream = null;
            Uri uri = null;
            try {
                Bundle extras = data.getExtras();
                Bitmap bitmap = null;
                if (extras != null) {
                    bitmap = (Bitmap) extras.get("data");
                }

                final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                uri = resolver.insert(contentUri,contentValues);

                if (uri == null) {
                    throw new IOException("Failed to create new MediaStore record.");
                }

                stream = resolver.openOutputStream(uri);

                if (stream == null) {
                    throw new IOException("Failed to get output stream.");
                }

                if (bitmap!=null && !bitmap.compress(Bitmap.CompressFormat.JPEG,95,stream)) {
                    throw new IOException("Failed to save bitmap.");
                }

                stream.close();

                selctedImageUri = String.valueOf(uri);

                Glide.with(getActivity()).load(uri).into(imageProfile);

            } catch (IOException e) {
                if (uri != null) {
                    // Don't leave an orphan entry in the MediaStore
                    resolver.delete(uri,null,null);
                }
                e.printstacktrace();
            }
        }
    }






@Override
    public void onActivityResult(int requestCode,int resultCode,Intent data) {
        CgUtils.showLog(getTag(),"frag onActivityResult");

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == TAKE_PICTURE) {
                CgUtils.showLog(getTag(),"frag TAKE_PICTURE");

                if (checkIfVersionCodeQAndAbove()) {
                    storeImageUsingMediaApi(data);
                } else {
                    Uri imageUri = Uri.parse(selctedImageUri);
                    if (imageUri.getPath() != null) {
                        File file = new File(imageUri.getPath());
                        try {
                            InputStream ims = new FileInputStream(file);
                            imageProfile.setimageBitmap(BitmapFactory.decodeStream(ims));
                        } catch (FileNotFoundException e) {
                            CgUtils.showLog(TAG,"error " + e.toString());
                        }
                    }
                }
                if (!selctedImageUri.isEmpty()) {
                    if (null != loginResponse)
                        loginResponse.setimageUri(selctedImageUri);
                    new InsertLoginResponse(getActivity(),loginResponse,false).executeOnExecutor(CgUtils.getExecutorType());

                    sharedPreferencesEditor.putString(CgConstants.USER_PROF_PIC,selctedImageUri);
                    sharedPreferencesEditor.commit();
                }
            }
      }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)