歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android將圖片保存到相冊並及時看到

Android將圖片保存到相冊並及時看到

日期:2017/3/1 9:29:48   编辑:Linux編程

Android中將圖片保存到SD卡中,相冊裡不會及時出現這張圖片,因為沒有及時更新其索引,一般需要開機幾次。當然我們可以手動更新其索引。

1,首先將文件保存到SD卡中。

String filePath = "xxx"; //全路徑

saveImgToSDcard(filePath);

2,增加Android 內部媒體索引。

public boolean saveImgToGallery(String filePath) {

    boolean sdCardExist = Environment.getExternalStorageState().equals(

    android.os.Environment.MEDIA_MOUNTED); // 判斷sd卡是否存在

    if (!sdCardExist)

      return false;

      try {

        ContentValues values = new ContentValues();

        values.put("datetaken", new Date().toString());

        values.put("mime_type", "image/jpg");

        values.put("_data", filePath);

        Application app = DoctorApplication.getInstance();

        ContentResolver cr = app.getContentResolver();

        cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

      } catch (Exception e) {

        e.printStackTrace();

      }

      return true;

    }

3,刷新filePath的上一級目錄

MediaScannerConnection.scanFile(MyLanJingCode.this,new String[] { Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath()+ "/"+ filePath.getParentFile().getAbsolutePath() }, null,null);

這樣就能及時在相冊中看到增加的圖片了。

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved