1.保存圖片的方法
public static StringSaveImage(Bitmap finalBitmap,String filename) {
String path="";
? ? String root = Environment.getExternalStorageDirectory().toString();
? ? File myDir =new File(root +"/xqFile");
? ? myDir.mkdirs();
? ? String fname = filename;
? ? File file =new File (myDir, fname);
? ? if (file.exists ()) file.delete ();
? ? try {
file.createNewFile();
? ? ? ? path=file.getAbsolutePath();
? ? ? ? FileOutputStream out =new FileOutputStream(file);
? ? ? ? finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
? ? ? ? out.flush();
? ? ? ? out.close();
? ? }catch (Exception e) {
e.printStackTrace();
? ? }
return path;
}
這樣圖片可以保存,但是有得機型在文件夾下不能及時看到生成圖片。這種現(xiàn)象是少了給手機媒體庫通知造成的。
2.刪除圖片
public static void deleteFile(String fileurl)throws Exception{
File dir =new File(fileurl);
? ? if (dir.isFile())
dir.delete();
}
這種方法刪除圖片,發(fā)現(xiàn)在有的機型還是能看到,改用以下方法刪除圖片
public static void deleteImageMedia(final Context context,String filePath){
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
? ? ContentResolver mContentResolver = context.getContentResolver();
? ? String where = MediaStore.Images.Media.DATA +"='" + filePath +"'";
? ? //刪除圖片
? ? mContentResolver.delete(uri, where, null);
}
以上方法能正常刪除,但是發(fā)現(xiàn)刪除了,有的機型還是能看到。這種問題也會缺少給媒體庫發(fā)送通知
3.給媒體庫發(fā)送通知
可以在生成圖片或者刪除圖片以后加上以下方法
public static void updateMediaStore(final Context context, final String path) {
//版本號的判斷? 4.4為分水嶺,發(fā)送廣播更新媒體庫
? ? if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
MediaScannerConnection.scanFile(context, new String[]{path}, null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Intent mediaScanIntent =new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
? ? ? ? ? ? ? ? mediaScanIntent.setData(uri);
? ? ? ? ? ? ? ? context.sendBroadcast(mediaScanIntent);
? ? ? ? ? ? }
});
? ? }else {
File file =new File(path);
? ? ? ? String relationDir = file.getParent();
? ? ? ? File file1 =new File(relationDir);
? ? ? ? context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile(file1.getAbsoluteFile())));
? ? }
}
加上以上方法發(fā)現(xiàn)可以正??吹缴蓤D片,刪除的圖片也及時消失了