2

我正在从 SQL 数据库下载安卓设备上的图片;一切正常,除了打开 Stream 需要很长时间(即使没有图片可下载)。在实际下载开始之前大约需要 5 秒。这是我的代码片段:

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());给出了问题。关于如何加快速度的任何想法?

4

3 回答 3

4

这就是创建实际 TCP 连接的地方。这是网络问题,不是编码问题。您无法在代码中执行任何操作来修复它。

于 2012-06-12T22:00:41.050 回答
3

我使用此代码从 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); 
于 2012-06-12T22:02:25.297 回答
-1

url.openStream()在创建 时调用InputStream,但在此之前您正在创建新连接并调用connection.connect()

来自android JavaDoc: openStream()是“等效于openConnection().getInputStream(types)

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

总之,我认为您应该connection.getInputStream()在初始化InputStream.

于 2012-10-02T10:38:31.883 回答