Android custom camera photos not shown in gallery

2019-08-08 04:49发布

问题:

I'm creating custom android camera layout.

I've used information from http://developer.android.com/guide/topics/media/camera.html#basics. Everithing works fine except one thing.

The photo is not shown in the phone's gallery. The metod is:

private Camera.PictureCallback cameraCallback = new Camera.PictureCallback() {

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

        File pictureFile = getOutputMediaFile();
        if (pictureFile == null){
            Log.d(Values.APPLICATION_TAG + ACTIVITY_TAG, "Error creating media file, check storage permissions: ");
            return;
        }

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.flush();
            fos.close();
            createPhotoAndShowPreview(Uri.fromFile(pictureFile));
        } catch (FileNotFoundException e) {
            Log.d(Values.APPLICATION_TAG + ACTIVITY_TAG, "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d(Values.APPLICATION_TAG + ACTIVITY_TAG, "Error accessing file: " + e.getMessage());
        }
    }
};

private static File getOutputMediaFile(){

    File galleryDir = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "MyCameraApp"); 
    if (!galleryDir.exists()) {
        if (!galleryDir.mkdir())
        {
            Log.d(Values.APPLICATION_TAG, "failed to create directory");
            return null;
        }
    }

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    mediaFile = new File(galleryDir.getPath() + File.separator +
            "gfranq_"+ timeStamp + ".jpg");

    return mediaFile;
}

Method createPhotoAndShowPreview(Uri.fromFile(pictureFile)); works fine, the file exists during runtime and I can use it, but when I exit the app there is no file in the gallery. I used a file manager to check if the file is deleted, but its not deleted, it exists after exiting the application, but the system doesn't recognize that it is an image.

Update: The photos appered in the gallery after I connected my phone to my pc. But new photos still don't appear in the gallery untill I connect and disconnect my phone to pc. rebooting the phone has the same effect.

回答1:

You need to send out a broadcast:

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageFile)));



回答2:

MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
            new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Log.i("ExternalStorage", "Scanned " + path + ":");
                    Log.i("ExternalStorage", "-> uri=" + uri);
                }
            });