如何在Android Q上将照片广播到画廊 [英] How to broadcast photo to gallery on Android Q

查看:255
本文介绍了如何在Android Q上将照片广播到画廊的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这些代码拍摄照片并将照片广播到画廊,它可以正常工作。

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

我发现我的广播功能使用 MediaStore .Images.ImageColumns.DATA Intent.ACTION_MEDIA_SCANNER_SCAN_FILE ,这些已弃用!

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

如何在不使用 MediaStore.Images.ImageColumns.DATA Intent.ACTION_MEDIA_SCANNER_SCAN_FILE 的情况下替换这些功能。

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

谢谢。

// 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);
    }


推荐答案

没有必要先将图片文件保存在某个位置,然后尝试将其插入MediaStore。您可以从MediaStore中获取一个uri(就像现在从FileProvder中获取的一样),然后让Camera应用程序使用它。不需要清单和运行时代码中的WRITE权限。

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;
                }

在其中使用 insertUri 通过onActivityResult()处理图片。

Use insertUri in onActivityResult() to handle the picture.

图片位于图片目录中。取消注释RELATIVE_PATH行之一以将它们放置在其他位置。将创建子目录。

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

适用于低于Q的版本。

这篇关于如何在Android Q上将照片广播到画廊的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆