捕获图像后更新图库 android

Update Gallery after capture an image android

我尝试创建一个可以从相机捕获图像并根据图像路径显示结果的应用程序。在处理捕获图像的按钮内,如下所示

btnImg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

                file = new File(Environment.getExternalStorageDirectory() + File.separator + "Nama_foto_" + waktu + ".jpg");

                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                intent.putExtra("return-data", true);

                getParentFragment().startActivityForResult(intent, CAPTURE_IMAGE);
            }catch (ActivityNotFoundException anfe){
                //display an error message
                String errorMessage = "Whoops - your device doesn't support capturing images!";
                Toast toast = Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT);
                toast.show();
            }
        }
    });

作为相机捕捉的回应,我正在写下面的代码

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if(requestCode == CAPTURE_IMAGE) {

            performCrop();
        }
        else if(requestCode == PIC_CROP){
            //get the returned data
            Bundle extras = data.getExtras();
            //get the cropped bitmap
            Bitmap thePic = extras.getParcelable("data");

            picturePath = file.getAbsolutePath();

            try {
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                thePic.compress(Bitmap.CompressFormat.JPEG, 80, bytes);

                file.createNewFile();
                FileOutputStream out = new FileOutputStream(file);
                out.write(bytes.toByteArray());
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            //retrieve a reference to the ImageView
            //ImageView picView = (ImageView)findViewById(R.id.picture);
            //display the returned cropped image
        imgView.setImageBitmap(thePic);
        }

        try {

        }catch (Exception e) {
            Toast.makeText(getActivity(), "Maaf gagal mengambil foto.", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
}

}

在 OnCreateView 外部声明为空字符串的变量 picturePath。 问题是,每当我 运行 应用程序并捕获图像时。图片没有立即显示在图库中,但我需要重新 运行 应用程序(通过 android studio)才能在图库中看到图片。好像 oncreateview 里面的东西触发了事件。但是我还是想不通。

请帮我解决这个问题。谢谢

您的问题似乎应该换一种说法: 这可能会解决您的问题

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));

参考: How can I update the Android Gallery after a photo?