关于安卓下载管理器的小问题。
这是我第一次使用它,并成功下载了多个文件并打开它们。但我的问题是如何检查下载是否完成。
情况是我下载了一个 PDF 文件并打开它,通常该文件很小,在打开之前就完成了。但是,如果文件较大,如何在打开文件之前检查下载管理器是否已完成下载。
我如何下载:
Intent intent = getIntent();
DownloadManager downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
Uri Download_Uri = Uri.parse(intent.getStringExtra("Document_href"));
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
//Restrict the types of networks over which this download may proceed.
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
//Set whether this download may proceed over a roaming connection.
request.setAllowedOverRoaming(false);
//Set the title of this download, to be displayed in notifications.
request.setTitle(intent.getStringExtra("Document_title"));
//Set the local destination for the downloaded file to a path within the application's external files directory
request.setDestinationInExternalFilesDir(this,Environment.DIRECTORY_DOWNLOADS,intent.getStringExtra("Document_title") + ".pdf");
//Enqueue a new download and same the referenceId
Long downloadReference = downloadManager.enqueue(request);
我如何打开文件
Uri uri = Uri.parse("content://com.app.applicationname/" + "/Download/" + intent.getStringExtra("Document_title") + ".pdf");
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(uri, "application/pdf");
target.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(target);
因此,在下载和打开文件之间的某个位置,我想要一个 if 语句来检查它是否应该继续或等待文件。
广播由DownloadManager
每当下载完成时,您需要使用适当的意图操作( ACTION_DOWNLOAD_COMPLETE )注册广播接收器来捕获此广播:
注册接收者
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
和一个 BroadcastReciever 处理程序
BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
// your code
}
};
您还可以创建AsyncTask来处理大文件的下载
创建某种下载对话框以在通知区域中显示下载并处理文件的打开:
protected void openFile(String fileName) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(Uri.fromFile(new File(fileName)),"MIME-TYPE");
startActivity(install);
}
您还可以检查示例链接
示例代码
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)