2014-07-20 66 views
0

我是新的android。我想將圖片從網址保存到SDcard。如何將圖像保存到SD卡從Url android

File direct = new File(Environment.getExternalStorageDirectory() 
       + "/.imgapp"); 

    if (!direct.exists()) { 
      direct.mkdirs(); 
     } 
     Calendar c = Calendar.getInstance(); 
     int d = c.get(Calendar.DATE); 
     int d1 = c.get(Calendar.MONTH)+1; 


     File file = new File(Environment.getExternalStorageDirectory() 
       + "/.imgapp/"+d+""+d1+".png"); 
     if (!file.exists()) { 
      URL url = new URL ("file://some/path/anImage.png"); 
      InputStream input = url.openStream(); 

     try { 

      OutputStream output = new FileOutputStream (Environment.getExternalStorageDirectory() 
       + "/.imgapp/"+d+""+d1+".png"); 

     try { 
      byte[] buffer = new byte[aReasonableSize]; 
      int bytesRead = 0; 

     while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) { 
       output.write(buffer, 0, bytesRead); 
       } 
      } finally { output.close(); } 
      } finally { input.close(); } 

     }else{ 
      Toast.makeText(getApplicationContext(), "No Error", Toast.LENGTH_SHORT).show(); 

     } 

清單文件

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

我嘗試這種代碼,但應用程序停機和故障,請幫助我。 我想要下載圖像onCreate當用戶打開應用程序。

+0

什麼是錯誤?安裝logcat來查看錯誤。 – iMBMT

回答

0

終於完成!!

DownloadManager mgr = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE); 

      String uRl = "http://bitsparrow.altervista.org/wp-content/uploads/2013/04/5.jpg"; 
     Uri downloadUri = Uri.parse(uRl); 
      DownloadManager.Request request = new DownloadManager.Request(
        downloadUri); 

      request.setAllowedNetworkTypes(
        DownloadManager.Request.NETWORK_WIFI 
          | DownloadManager.Request.NETWORK_MOBILE) 
        .setAllowedOverRoaming(false).setTitle("Demo") 
        .setDescription("Something useful. No, really.") 
        .setDestinationInExternalPublicDir("/.appimg", "test.jpg"); 

      mgr.enqueue(request); 

This Work For me ..!