如何使用Android Download Manager进行文件下载和数据存储[页8]
2023-08-23次
javaString url = "http://example.com/myfile.mp3";
String filename = "myfile.mp3";
String filepath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
request.setTitle("Downloading " + filename);
request.setDescription("Downloading " + filename);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
long downloadId = downloadManager.enqueue(request);
BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(id);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
String localFilePath = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
// Do something with the downloaded file
} else {
// Handle download failure
}
}
}
}
};
registerReceiver(downloadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
在这个例子中,我们创建了一个DownloadManager.Request对象,并设置了要下载的文件URL、保存路径、文件名以及通知信息。然后,我们将请求添加到Download Manager服务中,并获取了一个下载ID。接下来,我们注册了一个BroadcastReceiver来监听下载完成广播,并处理下载结果。