How to broadcast photo to gallery on Android Q

牧云@^-^@ 提交于 2019-12-25 01:49:43

问题


I use these code to take a photo and broadcast the photo to gallery, it works.

I found that my broadcast function use MediaStore.Images.ImageColumns.DATA and Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, and these are deprecated!

How can I replace these function without use MediaStore.Images.ImageColumns.DATA and Intent.ACTION_MEDIA_SCANNER_SCAN_FILE.

Thank you.

// set open camera button.
private void setCameraButton() {
    cameraBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ActivityCompat.requestPermissions(PostActivity.this, mPermissionList, CAMERA_REQUEST_PERMISSION);
        }
    });
}


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode){
        case 100: // camera.
            if(grantResults.length > 0){
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
                    openCameraIntent();
                else
                    Toast.makeText(this, "Please set permissions.", Toast.LENGTH_SHORT).show();
            }
            break;

            ...
        }
    }

private void openCameraIntent() {
    Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (pictureIntent.resolveActivity(getPackageManager()) != null) {
        String time = MyUtility.getSystemTaiwanDateAndTime();
        photoFileName = "IMG_" + time;

        File storageDir = new File(this.getExternalFilesDir(null).getAbsolutePath(), "myapp");
        MyUtility.createAppFolder(storageDir); // create app folder.

        photoFile = new File(this.getExternalFilesDir(null).getAbsolutePath(), "/myapp/" + photoFileName + ".jpg");

        Uri photoUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", photoFile);
        pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        startActivityForResult(pictureIntent, IMAGE_CAPTURE_REQUEST_CODE);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == IMAGE_CAPTURE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        photoFilePath = photoFile.getAbsolutePath();
        broadcastAddPhotoToGallery(photoFile, photoFileName, photoFilePath); // Want to use this function to broadcast photo to gallery.

        ...
    }
        ...
}

private void broadcastAddPhotoToGallery(File _file, String _fileName, String _filePath) {

    int sdkVersion = Build.VERSION.SDK_INT;
    if(sdkVersion >= 28) 
        galleryAddPhotoAboveApi28(_fileName, _filePath);
    else 
        galleryAddPhotoBelowApi28(String.valueOf(_file));
}


private void galleryAddPhotoAboveApi28(String _fileName, final String _filePath) {

    OutputStream out = null;
        try {
            ContentValues values = new ContentValues();
            ContentResolver resolver = this.getContentResolver();

            values.put(MediaStore.Images.ImageColumns.DATA, _filePath); // MediaStore.Images.ImageColumns.DATA is deprecated!
            values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, _fileName);
            values.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/jpg");
            values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, System.currentTimeMillis() + "");
            Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            if (uri != null) {
                Bitmap bitmap = BitmapFactory.decodeFile(_filePath);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

private void galleryAddPhotoBelowApi28(String _file) {
        File f = new File(_file);
        Uri contentUri = Uri.fromFile(f); 
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, contentUri); // Intent.ACTION_MEDIA_SCANNER_SCAN_FILE is deprecated!
        sendBroadcast(mediaScanIntent);
    }

回答1:


There is no need to first save a picture file somewhere and then trying to insert it in the MediaStore. You can get an uri form the MediaStore (like you get it now from a FileProvder) and let that be used by the Camera app. No need for WRITE permissions in manifest and runtime code.

        if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
                {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    ContentValues values = new ContentValues(3);

                    String displayName =  "FromTakepicture." + System.currentTimeMillis() + ".jpg";

                    values.put(MediaStore.Images.Media.DISPLAY_NAME, displayName);
                    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");

                    //values.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/playground");
                    //values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/playground");

                    insertDisplayName = displayName;
                    insertUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

                    intent.putExtra(MediaStore.EXTRA_OUTPUT, insertUri);

                    startActivityForResult(intent, PICK_PHOTO_CODE_URI);

                    return;
                }

Use insertUri in onActivityResult() to handle the picture.

The pictures land in the Pictures directory. Uncomment one of the RELATIVE_PATH lines to put them somewhere else. The subdirectory will be created.

Adapt for versions below Q.



来源:https://stackoverflow.com/questions/59187727/how-to-broadcast-photo-to-gallery-on-android-q

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!