DownloadManager是Android提供的一个系统组件,可以在后台异步下载文件,且支持断点续传等特性。使用DownloadManager进行下载可以提高下载速度和稳定性。
示例代码:
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); Uri uri = Uri.parse("http://example.com/file.apk"); DownloadManager.Request request = new DownloadManager.Request(uri); request.setAllowedOverRoaming(false); request.setTitle("文件下载"); request.setDescription("正在下载..."); request.setVisibleInDownloadsUi(true); request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, "file.apk"); downloadManager.enqueue(request);
有些服务器会根据User-Agent头返回不同的数据,为了获得更好的下载速度,可以设置合适的User-Agent头。
示例代码:
URL url = new URL("http://example.com/file.apk"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:108.0) Gecko/20100101 Firefox/108.0"); InputStream in = conn.getInputStream();
多线程下载可以有效提高下载速度,但需要注意线程数的设置以及分块的大小。
示例代码:
URL url = new URL("http://example.com/file.apk"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); int contentLength = conn.getContentLength(); int threadNum = 3; int blockSize = contentLength / threadNum;
for (int i = 0; i < threadNum; i++) { int start = i * blockSize; int end = (i + 1) * blockSize - 1; new DownloadThread(url, start, end).start(); }
其中DownloadThread是自定义的下载线程类,用于下载指定区间的数据。