应用中,用户在浏览图片时通常会需要保存图片的功能,即将应用中喜欢的图片保存到手机系统相册中。
Android系统提供了对应的API来实现这个功能:
MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "", "");
通过上述代码便能将Bitmap对象保存到系统相册的图片中,但是有两点需要注意:
第一点:
虽然系统提供的两个API:
或者MediaStore.Images.Media.insertImage(ContentResolver cr, Bitmap source, String title, String description)
提供了title和description参数,我们依旧不能指定保存到相册中图片的名字,系统会默认使用当前时间的毫秒数作为图片名。MediaStore.Images.Media.insertImage(ContentResolver cr, String imagePath, String name, String description)
第二点:
保存完图片后,可以在内存设备的文件系统相册目录下看到对应图片(以小米手机为例,系统相册的路径为:/storage/emulated/0/DCIM/Camera)。但是,使用系统图库无法马上看到该图片,需要重启手机才能看到,因为保存图片后没有更新图库的缘故。可以在保存图片后使用如下解决方案:
解决方案一:发送扫描广播(过时)
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
上面那条广播是扫描整个sd卡的广播,如果你sd卡里面东西很多会扫描很久,在扫描当中我们是不能访问sd卡,所以这样子用户体现很不好,用过微信的朋友都知道,微信保存图片到系统相册并没有扫描整个SD卡,所以我们用到下面的方法:Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri uri = Uri.fromFile(new File("/sdcard/image.jpg")); intent.setData(uri); mContext.sendBroadcast(intent);
请注意,在第一种方案后面我标记了“过时”,因为发送这条扫描广播,需要android.intent.action.MEDIA_MOUNTED系统权限,但是再Android 4.4系统以后,限制了只有系统应用才有使用广播通知系统扫描的权限,否则会抛出异常信息:Permission Denial: not allowed to send broadcast android.intent.action.MEDIA_MOUNTED
所有有了第二种解决方案。
解决方案二:使用MediaScannerConnection
然后调用msc.connect()方法扫描即可!final MediaScannerConnection msc = new MediaScannerConnection(mContext, new MediaScannerConnectionClient() { public void onMediaScannerConnected() { msc.scanFile("/sdcard/image.jpg", "image/jpeg"); } public void onScanCompleted(String path, Uri uri) { msc.disconnect(); } });
其中,图片的路径是根据调用insertImage时返回Uri字符串转换而来的,通过Uri.parse(String uriString)方法获取Uri对象,然后通过如下方法获取图片在相册中的文件路径:
/** * 根据Uri获取图片路径 * @param context * @param uri * @return */ public static String getFilePathByContentResolver(Context context, Uri uri) { if (null == uri) { return null; } Cursor c = context.getContentResolver().query(uri, null, null, null, null); String filePath = null; if (null == c) { throw new IllegalArgumentException( "Query on " + uri + " returns null result."); } try { if ((c.getCount() != 1) || !c.moveToFirst()) { } else { filePath = c.getString( c.getColumnIndexOrThrow(MediaColumns.DATA)); } } finally { c.close(); } return filePath; }