ZWate 2017-02-08 02:28 采纳率: 0%
浏览 2166

关于使用HttpURLConnection下载大文件的一些问题(UI卡顿) 求大神指导

下面是我的函数
private void getFile() {
new Thread(new Runnable() {
@Override
public void run() {
synchronized (this) {
URL url = null;
InputStream inputStream = null;
FileOutputStream outputStream = null;
long fileSize = 0;
try {
url = new URL(downloadUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(28000);
connection.setRequestMethod("GET");
if (connection.getResponseCode() == 200) {
inputStream = connection.getInputStream();
File file = new File(Environment.getExternalStorageDirectory() + "/" + directoriy, filename);
outputStream = new FileOutputStream(file);
fileSize = connection.getContentLength();
int length = 0;
byte[] buffer = new byte[1024];
int downloadSize = 0;
while ((length = inputStream.read(buffer)) != -1) {
downloadSize = downloadSize + length;
progress[0] = downloadSize / (float) fileSize;
outputStream.write(buffer, 0, length);
handler.sendEmptyMessage(INVALIDATE1);
}
outputStream.flush();
outputStream.close();
handler.sendEmptyMessage(LOAD_SUCCESS1);
}
} catch (MalformedURLException e) {
handler.sendEmptyMessage(LOAD_ERROR1);
e.printStackTrace();
e.getMessage();
try {
if (inputStream != null)
inputStream.close();
if (outputStream != null)
outputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (IOException e) {
handler.sendEmptyMessage(LOAD_ERROR1);
e.printStackTrace();
if (inputStream != null)
try {
inputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
if (outputStream != null)
try {
outputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}).start();

}

用上面的函数下载一个1个G的文件要改成POST方式吗?需要的话函数需要拿些改动呢,还有就是下载启动大文件之后对UI有很大的影响,列表直接卡住了,想请问用什么方法可以优化一下呢?

  • 写回答

2条回答 默认 最新

  • oyljerry 2017-02-08 02:47
    关注

    你已经在线程中下载文件了,不会直接影响UI,一个可能就是你的数据太多,然后更新UI列表的时候导致处理负荷太重。可以降低列表刷新等。

    评论

报告相同问题?

悬赏问题

  • ¥15 计算二重积分∫∫e^(x+y)dxdy,其中0≤x≤1,0≤y≤1,试分别用复合辛普森公式(取n=4)以及高斯求积公式(取n=4)计算积分 给出matlab程序
  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的