安卓儲存網絡圖檔并通知圖庫更新
最近有個需求剛好是這個,但是發現網絡圖檔儲存到手機後圖庫并沒有及時重新整理出來,搗鼓了一上午終于搞出來了
廢話不說直接上代碼:
首先是寫個異步請求網絡圖檔
// 異步任務 直接傳圖檔位址
public void addTask(String url) {
new AsyncTask<String, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(String... params) {
// 背景通信
return decodeBitmap(params[]);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
// 主線程處理view
if (bitmap != null) {
//儲存
saveImageToGallery(context, bitmap);
}
}
}.execute(url);
}
接着是url 轉為bitmap的方法
/**
* url 到 bitmap
* @param httpUrl
* @return
*/
private Bitmap decodeBitmap(String httpUrl) {
URL url = null;
Bitmap bm = null;
try {
url = new URL(httpUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
InputStream in = url.openStream();
bm = BitmapFactory.decodeStream(in);
} catch (IOException e) {
e.printStackTrace();
}
return bm;
}
接下來是儲存bitmap到本地通知圖庫的方法
/**
* 儲存圖檔到圖庫的方法
*
* @param context
* @param bmp
*/
public void saveImageToGallery(Context context, Bitmap bmp) {
// 首先儲存圖檔
File appDir = new File(Environment.getExternalStorageDirectory(), "picdir");
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, , fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 其次把檔案插入到系統圖庫
try {
Toast.makeText(context, "儲存圖檔", Toast.LENGTH_SHORT).show();
MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
} catch (Exception e) {
e.printStackTrace();
}
// 最後通知圖庫更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/picdir")));
// Uri uri = Uri.fromFile(file); //file 是你圖檔的路徑 直接更新圖檔的路徑更好(建議使用)
// context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
Toast.makeText(context, "圖庫更新成功", Toast.LENGTH_SHORT).show();
}
附上調用的片段吧:
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiQ3chVEa0V3bT9CX5RXa2Fmcn9CXwczLcVmds92czlGZvwVP9EUTDZ0aRJkSwk0LcxGbpZ2LcBDM08CXlpXazRnbvZ2LcRlMMVDT2EWNvwFdu9mZvwVNohVZ2g3RjZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39jM1QTO0UTN0EDOxgDM3EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
好了,就是如此簡單.注意6.0以上直接通路讀寫檔案需要注意檢查權限!!!