首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android MediaStore 插入圖片失敗:需發送廣播通知媒體掃描器

     編輯:程式設計綜合問答

常見遺漏

向 MediaStore.Images.Media.insertImage 寫入後,必須發送廣播讓系統媒體掃描器更新資料庫,否則圖庫、QQ 等無法立即看到。

正確代碼


String path = Images.Media.insertImage(getContentResolver(), bitmap, title, description);
if (path != null) {
    Uri uri = Uri.parse(path);
    // 發送廣播掃描單一文件
    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
}

或儲存檔案後:


File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "pic.jpg");
// 存檔...
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));

Android 10+ (Q) 建議使用 MediaStore API 直接插入,無需掃描廣播。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved