2012-06-12 268 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()