2012-06-12 266 views
1

我正在從一個SQL數據庫的android設備上下載圖片;除了打開Stream需要很長時間(即使沒有下載圖片),一切都運行良好。實際下載開始前大約需要5秒。這裏是我的代碼片段:URL.openStream非常慢

URL url = new URL(sUrl[0]); 
URLConnection connection = url.openConnection(); 
connection.connect(); 

int fileLength = connection.getContentLength(); 

//input = connection.getInputStream(); 
InputStream input = new BufferedInputStream(url.openStream()); 


File file = new File(
     Environment 
       .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), 
     "MyCameraApp" + "/testpic.jpg"); 
OutputStream output = new FileOutputStream(file); 
byte data[] = new byte[1024]; 

//---blabla progressbar update etc.. 

InputStream input = new BufferedInputStream(url.openStream());給出了這個問題。任何想法如何加快速度?

+0

您是否確定延遲發生在該聲明中?我期望它發生在connect()調用中。 –

回答

4

我使用此代碼從url獲取位圖。 :)

Bitmap bitmap = null; 
    URL imageUrl = new URL(url); 
    HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection(); 
    conn.setConnectTimeout(30000); 
    conn.setReadTimeout(30000); 
    InputStream is = conn.getInputStream(); 
    OutputStream os = new FileOutputStream(f); 

try 
{ 
    byte[] bytes=new byte[1024]; 
    for(;;) 
    { 
     int count=is.read(bytes, 0, 1024); 
     if(count==-1) 
     break; 
     os.write(bytes, 0, count); 
    } 
} 
catch(Exception ex){} 
os.close(); 
bitmap = decodeFile(f); 
+3

不回答問題。 – EJP

+2

實際上,它的速度大概是2-3秒。謝謝!也許使用HTTPURLConnection可以加快速度。 – user1337210

3

這就是創建實際TCP連接的點。這是一個網絡問題,而不是編碼問題。沒有什麼可以在代碼中進行修復。

+0

實際上,TCP連接早些時候做了一個聲明......因爲他會得到內容的長度。但是你可能是正確的,這只是網絡延遲,並且在Java客戶端代碼中沒有解決這個問題。 –

+0

@StephenC是的。在這種情況下,它必須是花費時間的'getContentLength()'。 – EJP

0

創建InputStream當你調用url.openStream(),但在此之前,你要創建一個新的連接和呼叫connection.connect()

從Android的JavaDoc:openStream()是 「相當於openConnection().getInputStream(types)

http://developer.android.com/reference/java/net/URL.html#openStream()

綜上所述,我認爲在初始化時InputStream你應該調用connection.getInputStream()