Images not being saved when picture is taken by camera app that isn't the stock camera

泪湿孤枕 提交于 2019-12-04 14:04:18

well ,
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); does not work anymore . you should do something like this : call Camera Activity :

  Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

and onActivityResult :

 if (data.getData() == null) {  
    Bitmap bm = (Bitmap)
  data.getExtras().get("data");
   String timeStamp = new SimpleDateFormat(
                            "yyyyMMdd_HHmmss").format(new Date());

  File pictureFile = new File(Environment
                            .getExternalStoragePublicDirectory(
                                    Environment.DIRECTORY_PICTURES)
                            .getAbsolutePath()
                            + File.separator + "IMG_" + timeStamp);

try {
     FileOutputStream fos = new FileOutputStream(
                                pictureFile);
    bm.compress(Bitmap.CompressFormat.JPEG, 90, fos);
    fos.close();
     String filePath = pictureFile.getAbsolutePath();
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   } catch (IOException e) {
   e.printStackTrace();
   }   } else {

   Uri imgUri =data.getData());  

}

It turns out my code was working after all. The pictures were being saved in the new directory, but the problem was that the gallery wasn't being updated, which explains why the photos would randomly appear in the directory later on. Being new to this, it never occurred to me that I would have to update the gallery. I only came to this realization after using ES File Explorer to look through my files. To fix my problem, I just made a new method in my CameraFragment that would call on the media scanner. I called this method from onActivityResult().

Here's the new method, though there's nothing really "new" about it since I ran into the same code on other SO questions:

protected void mediaScan() {
    getActivity().sendBroadcast(
            new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, 
                    Uri.parse(fileUri.toString())));
}

I also don't need to call the package manager and iterate through the apps that could handle the camera intent if I'm not giving the option to use choose a picture from a gallery, so I'm going to remove all that from my question.

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