android 手機圖片生成刪除不能及時看到效果問題

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片,刪除的圖片也及時消失了

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容