Android DownloadManager是一个系统服务,可以通过它在后台下载文件。可以使用以下步骤来使用DownloadManager:
创建DownloadManager.Request对象并设置下载URL,目标文件路径等选项。
调用DownloadManager.enqueue()方法将请求添加到下载队列中。
通过查询DownloadManager来获取下载进度和状态。可以使用DownloadManager.Query类和DownloadManager.Cursor类来查询已下载文件的信息。
以下是一个简单的示例代码:
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse("http://example.com/myfile.mp3");
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
request.setTitle("My File");
request.setDescription("Downloading");
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "myfile.mp3");
long downloadId = downloadManager.enqueue(request);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
String uriString = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
// Do something with the downloaded file
} else if (status == DownloadManager.STATUS_FAILED) {
// Handle download failure
}
}