Android 그림 은 앨범 에 표시 되 지 않 는 솔 루 션 으로 저 장 됩 니 다(Android 10 및 더 높 은 버 전 호 환)

머리말
demo 를 썼 습 니 다.간단 한 논 리 는 한 그림 에 텍스트 나 워 터 마크 를 추가 하고 시스템 앨범,즉 우리 핸드폰 의 갤러리 에 저장 하 는 것 입 니 다.앞에서 편집 한 그림 에 워 터 마크 를 추가 하 는 데 문제 가 없 으 며,뒤로 시스템 앨범 에 저장 하 는 데 문제 가 생 겼 습 니 다.그림 이 표시 되 지 않 습 니 다.
문제.
Android 10 이전에 시스템 앨범 을 저장 하 는 세 단계:
사진 을 핸드폰 에 저장 하 다.
사진 을 핸드폰 갤러리 에 삽입 하 다.
방송 업데이트
코드 는 다음 과 같 습 니 다:

public static void savePhotoAlbum(Context context, Bitmap bmp) {
    //       
    File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
    if (!appDir.exists()) {
        appDir.mkdir();
    }
    String fileName = System.currentTimeMillis() + ".jpg";
    File file = new File(appDir, fileName);
    try {
        FileOutputStream fos = new FileOutputStream(file);
        bmp.compress(CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
	}
    
    //             
    try {
        MediaStore.Images.Media.insertImage(context.getContentResolver(),
				file.getAbsolutePath(), fileName, null);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    //         
    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
}
문제:그림 이 표시 되 지 않 습 니 다.즉,시스템 갤러리 에 업데이트 되 지 않 았 습 니 다.
세심 한 동료 들 은 상단 코드 가 두 군데 폐기 되 는 방법 을 발견 할 수 있다.

 MediaStore.Images.Media.insertImage(context.getContentResolver(),
				file.getAbsolutePath(), fileName, null);

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
문 제 를 해결 하 다
다음은 위의 문 제 를 해결 하고 Android 10 버 전 을 호 환 합 니 다.

    /**
     *             
     */
    private void imgMerge() {
        new Thread(() -> {
            try {
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test);
                File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "newFile.jpg");
                if (!file.exists()) {
                    file.createNewFile();
                }
                //        。
                Bitmap newBitmap = addTextWatermark(bitmap, "  demo  ");
                //       
                savePhotoAlbum(newBitmap, file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
    
    /**
     *      
     *
     * @param src     
     * @param file        
     */
    private void savePhotoAlbum(Bitmap src, File file) {
        if (isEmptyBitmap(src)) {
            return;
        }
        //      
        OutputStream outputStream;
        try {
            outputStream = new BufferedOutputStream(new FileOutputStream(file));
            src.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            if (!src.isRecycled()) {
                src.recycle();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //     
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.MediaColumns.DISPLAY_NAME, file.getName());
            values.put(MediaStore.MediaColumns.MIME_TYPE, getMimeType(file));
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
            ContentResolver contentResolver = getContentResolver();
            Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,  values);
            if (uri == null) {
                return;
            }
            try {
                outputStream = contentResolver.openOutputStream(uri);
                FileInputStream fileInputStream = new FileInputStream(file);
                FileUtils.copy(fileInputStream, outputStream);
                fileInputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            MediaScannerConnection.scanFile(
                    getApplicationContext(),
                    new String[]{file.getAbsolutePath()},
                    new String[]{"image/jpeg"},
                    (path, uri) -> {
                        // Scan Completed
                    });
        }
    }
라디오 를 보 내 는 것 과 MediaProvider 를 삽입 하 는 두 가지 방식 으로 사진 을 앨범 에 추가 하 는 것 은 공식 적 으로 폐기 되 었 습 니 다.Android 10 버 전과 더 높 은 버 전에 서 위의 방법 을 사용 해 야 그림 이 표시 되 지 않 는 문 제 를 효과적으로 해결 할 수 있 습 니 다.
기록 해!
이상 은 안 드 로 이 드 이미지 가 시스템 앨범 에 저장 되 어 표시 되 지 않 는 솔 루 션(안 드 로 이 드 10 및 더 높 은 버 전 호 환)의 상세 한 내용 입 니 다.안 드 로 이 드 이미지 가 앨범 에 저장 되 어 표시 되 지 않 는 자 료 는 다른 관련 글 을 주목 하 십시오!

좋은 웹페이지 즐겨찾기