Android中的DownloadManager是一个系统服务,用于在后台下载文件并管理下载任务。要使用DownloadManager进行文件下载,可以按照以下步骤进行:
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://example.com/file.jpg"));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "file.jpg");
request.setTitle("File Download");
request.setDescription("Downloading file...");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
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));
int progress = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
int total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
}
downloadManager.remove(downloadId);
需要注意的是,为了使用DownloadManager进行文件下载,需要添加相应的权限到AndroidManifest.xml文件中:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
以上就是使用DownloadManager进行文件下载的基本步骤,通过DownloadManager可以方便地进行文件下载,并可以在后台管理下载任务的状态和进度。