为什么真机测试时会下载到某个百分比就卡住??请教CountDownLatch 用法?请教RandomAccessFile用法?可以运用下载到手机内存中吗?? 请教如何让UI界面流畅?因为我开始下载后UI界面很卡。 再请教如何让下载速度提高问题??麻烦高手指点!!解决一个问题是一个谢谢咯!!!private CountDownLatch latch = new CountDownLatch(THREAD_COUNT);。try { URL url = new URL(downloadUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET"); if (conn.getResponseCode() == 200) {
fileSize = conn.getContentLength();
if (fileSize <= 0)
throw new RuntimeException("Unkown file size ");
if (!Utility.isEnoughForDownload(fileSize)) {
download();
} else { saveFile = new File(fileSaveDir, downloadFileName);// 构建保存文件 long packageLength = fileSize / THREAD_COUNT;// 每个线程要下载的字节数
long leftLength = fileSize % THREAD_COUNT;// 剩下的字节数 RandomAccessFile randomAccessFile = new RandomAccessFile(
saveFile, "rw"); count = 0;
long pos = 0;
for (int i = 0; i < THREAD_COUNT; i++) {
long endPos = pos + packageLength; new DownloadThread(url, randomAccessFile, pos, endPos)
.start();
if (leftLength > 0) {
endPos++;
leftLength--;
}
pos = endPos;
} finished = true;
latch.await();
// }else{
// download();
// } // long t8=System.currentTimeMillis();
// Log.i("timeTest","newfile "+String.valueOf(t8-t5)); } } else {
throw new RuntimeException("server no response ");
} } catch (MalformedURLException e1) { e1.printStackTrace();
} catch (ProtocolException e) { e.printStackTrace();
} catch (IOException e) { e.printStackTrace();
// } catch (InterruptedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
class DownloadThread extends Thread {
private URL url;
private RandomAccessFile file;
private long from;
private long end; /**
 * @param url
 *            下载的URL
 * @param file
 *            下载完成之后存储的文件
 * @param from
 *            当前线程对应文件的起始位置
 * @param end
 *            当前线程对应文件的结束位置
 */
DownloadThread(URL url, RandomAccessFile file, long from, long end) {
this.url = url;
this.file = file;
this.from = from;
this.end = end;
} public void run() {
try {
long pos = from;
byte[] buf = new byte[1024000]; HttpURLConnection cn = (HttpURLConnection) url.openConnection();
cn.setRequestProperty("Range", "bytes=" + from + "-" + end); InputStream is = cn.getInputStream();
int len; while ((len = is.read(buf)) > 0) { // synchronized (file) {
file.seek(pos);
file.write(buf, 0, len);
// }
pos += len;
count += len; finishPercent = count * 100 / fileSize;
Log.e(TAG, "run" + Thread.currentThread().getId() + " "
+ String.valueOf(finishPercent));
mHandler.post(mUpdatePercent); }
cn.disconnect();
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, e.toString());
}
latch.countDown();
}
}