在Android 开发中,我们肯定会接触到下载需求,那么如何通过技术实现呢?
一、简单实现:
通过了解HTTP原理,我们应该可以知道,HTTP学习的时候,可以通过HTTPGET方式来进行文件下载:
new Thread(new Runnable() { @Override public void run() { String fileName = url.substring(url.lastIndexOf("/") + 1); // 如果不是,就加尾缀 if (!fileName.endsWith(MimeUtils.guessExtensionFromMimeType(mimetype))) { fileName = fileName + "." + MimeUtils.guessExtensionFromMimeType(mimetype); } // 限制文件名的长度 if (fileName.length() > 50) { fileName = fileName.substring(fileName.length() - 50); } HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 5 * 1000); HttpConnectionParams.setSoTimeout(params, 5 * 1000); HttpGet httpGet = new HttpGet(url); try { File file = new File(Environment.getExternalStorageDirectory(), fileName); if (!file.exists()) { file.createNewFile(); } else { boolean flag = file.delete(); if (flag) { file.createNewFile(); } else { // 目前设定是: 如果删除失败,就不进行下载了
return; } } RandomAccessFile randomFile = new RandomAccessFile(file, "rw"); HttpResponse response = new DefaultHttpClient(params).execute(httpGet); HttpEntity entity = response.getEntity(); InputStream in = entity.getContent(); randomFile.seek(randomFile.length()); byte[] buffer = new byte[1024]; int lenght = 0; while ((lenght = in.read(buffer)) > 0) { randomFile.write(buffer, 0, lenght); if (randomFile.length() == contentLength) { // 下载完成 } } randomFile.close(); httpGet.abort(); } catch (Exception e) { e.printStackTrace(); } } }).start();