Android 下載網絡圖片並提示圖庫更新

thread = new Thread(new Runnable() {
     @Override
     public void run() {
         String imageUrl = "http://img8.weixin05.com/20191116/662114/e7f181311acdb2e727e31b71b3ce7bef.jpeg?h=500&w=260";
         HttpGet httpRequest = new HttpGet(imageUrl);
         //取得HttpClient 對象
         HttpClient httpclient = new DefaultHttpClient();
         try {
             //請求httpClient ,取得HttpRestponse
             HttpResponse httpResponse = httpclient.execute(httpRequest);
             if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                 //取得相關信息 取得HttpEntiy
                 HttpEntity httpEntity = httpResponse.getEntity();
                 //獲得一個輸入流
                 InputStream is = httpEntity.getContent();
                 Bitmap bitmap = BitmapFactory.decodeStream(is);
                 is.close();
                 String fileName ;
                 String  bitName="sm.jpg";
                 try {
                     File file = new File(Environment.getExternalStorageDirectory( ).toString()+"/bbb");//僅創建路徑的File對象
                     if(!file.exists()){
                         file.mkdir();//如果路徑不存在就先創建路徑
                     }
                     fileName = Environment.getExternalStorageDirectory().getPath()+"/bbb/"+bitName ;
                     file = new File(fileName);
                     try {
                         FileOutputStream fos = new FileOutputStream(file);
                         bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                         fos.flush();
                         fos.close();
                     } catch (FileNotFoundException e) {
                         e.printStackTrace();
                     } catch (Exception e) {
                         e.printStackTrace();
                     }

   // 更新媒體庫
 
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)//版本號的判斷  4.4爲分水嶺,發送廣播更新媒體庫
{
    MediaScannerConnection.scanFile(App.getContext(), new String[]{file.getAbsolutePath()}, null, new MediaScannerConnection.OnScanCompletedListener() {
        public void onScanCompleted(String path, Uri uri) {
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            mediaScanIntent.setData(uri);
            App.getContext(). sendBroadcast(mediaScanIntent);
        }
    });
} else {
    App.getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile(file)));
}




                   
                 } catch (Exception e) {
                     e.printStackTrace();
                 }

             }

         } catch (ClientProtocolException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         } catch (Exception e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
 });
thread.start();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章