How to save media file in app specific folder using Media Store API - Scoped Storage Android

1.1k views Asked by At

I am trying to use scoped storage for Android 10 and above to save images taken from the camera in the app specific folder. I know how to do it using File API but I am looking for to do it with Media store API.

Here is the issue, using the below code it saves images in Internal storage > Pictures, but doesn't save it in app specific folder. Hence if I uninstall the app, the images saved by the app still remains in the memory. I want them to get deleted automatically if user removes the app from his phone.

Let me know if I am doing it wrong or missing something.

    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();
                }
            }
      }
}
0

There are 0 answers