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可以方便地進行文件下載,并可以在后臺管理下載任務的狀態和進度。