现在的位置: 首页 > 综合 > 正文

android 图片保存到系统相册,且将插入图片排序最前

2017年11月14日 ⁄ 综合 ⁄ 共 1719字 ⁄ 字号 评论关闭

突然我们的老大突发奇想,说把我们项目里面的图片保存到手机里面,方面用户查看。

马上开始上百度啊,很快,在网上看到一个大神:http://stormzhang.github.io/android/2014/07/24/android-save-image-to-gallery/

方法有二种,一种是使用系统提供的方法,

MediaStore.Images.Media.insertImage(context.getContentResolver(),file.getAbsolutePath(), fileName, null);
 // 最后通知图库更新1
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));

问题二:图片是插入图库饿了,但是新插入图片全显示在图片的后面。老大看了后要求将新插入的图片显示在最前面。这又花了我一下午的时间去研究,发现系统相册是根据图片的命名规则来排序的。所以我下载了android系统的相册源码,了解到它的命名规则。

SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd'_'HHmmss");

然后我就是使用了这样的方式给新插入的图片命名,可结果还是一样。


后来我突发奇想,使用了java io流的方式进行对图片插入图库,详细代码如下:
<pre name="code" class="java">private void testSaveImage(Bitmap tempbmp){
    	bmp = tempbmp;
    	new Thread(new Runnable() {
			@Override
			public void run() {
				String path = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DCIM + File.separator +"Camera";
		    	 // 首先保存图片
		    	Log.i("saveImage",""+path);
		        long now = System.currentTimeMillis();
				String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss").
			                format(new Date(now))+".jpg";
		        File file = new File(path, fileName);
		        FileOutputStream fos=null;
		        try {
		            fos = new FileOutputStream(file);
		            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
		            Log.i("saveImage","保存成功"+file.getAbsolutePath());
		            Intent intent = new Intent(
                            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		            Uri uri = Uri.fromFile(file);
		            intent.setData(uri);
		            sendBroadcast(intent);
		            GlobalApplication.showToastThread(getString(R.string.save_to_sysimg_text));
		            //sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
		        } catch (Exception e) {
		            e.printStackTrace();
		            Log.i("saveImage","保存失败");
		        }finally{
		        	try {
						fos.flush();
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
						
					}
		            
		        }
			}
		}).start();
    }

需要说明的是,在该方法里我使用了线程,主要是避免android的一个重要的ANR。


抱歉!评论已关闭.