android - 如何阻止 PDF 查看应用程序将以前的 PDF 保存在堆栈中?
问题描述
当我从 WebView 成功下载 PDF 时,我可以使用 VIEW 意图打开 PDF。当我按下后退按钮时,我会返回到我自己的应用程序。但是,当我下载并打开另一个 PDF 时,第一个 PDF 似乎仍在堆栈中。我必须按两次后退按钮才能返回我的应用程序。无论我使用主导航返回按钮还是 PDF 查看活动的标题栏中的按钮,这都是正确的。
我需要更改什么以确保只有我打开的 PDF 在堆栈上?
setDownloadListener { url, _, _, mimetype, _ ->
val downloadUri = Uri.parse(url)
val downloadRequest = DownloadManager.Request(downloadUri).apply {
setTitle("Title")
setDescription("Downloading file")
setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, downloadUri.lastPathSegment)
addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url))
}
val manager: DownloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val downloadId = manager.enqueue(downloadRequest)
registerReceiver(
object: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Log.w("onReceive", "${intent?.action}")
if (intent !== null && DownloadManager.ACTION_DOWNLOAD_COMPLETE == intent.action) {
val cursor = manager.query(DownloadManager.Query().apply{ setFilterById(downloadId) })
if (cursor.moveToFirst()) {
val downloadStatus = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
val downloadLocalUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))
val downloadMimeType = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE))
if (downloadStatus == DownloadManager.STATUS_SUCCESSFUL && downloadLocalUri !== null) {
val viewIntent = Intent(Intent.ACTION_VIEW).apply {
this.setDataAndType(Uri.parse(downloadLocalUri), downloadMimeType)
this.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
if (viewIntent.resolveActivity(packageManager) !== null) {
startActivity(
Intent.createChooser(viewIntent, "Choose app")
)
} else {
Toast.makeText(context, "No app available that can open file", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(context, "Unable to download file", Toast.LENGTH_SHORT).show()
Log.w("onReceive", "failure reason ${cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_REASON))}, ${cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))}")
}
}
}
}
},
IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
)
}
解决方案
推荐阅读
- c++ - 无法在构造函数中将变量作为参数传递(C++)
- c++ - 为什么 GDB 不能从带有信息符号的地址中找到符号?
- android - 如何在不继承 Material Components 主题的情况下使用 MaterialButtonToggleGroup
- c# - 如何在不破坏 C# 样式的情况下向现有段落添加文本?
- google-apps-script - 不确定我的问题的当前解决方案。可能希望在脚本中排除工作表 1。但对其他解决方案持开放态度
- c# - 在列表中的嵌套对象上创建查找
- python - 解释数据处理中的“多重共线性”
- swift - DRY 代码:如何从另一个协议调用实现
- python - 如何在循环中获取列表对象的内容而不是列表对象本身?
- google-apps-script - DriveApp.getUrl 返回“在对象驱动器中找不到函数 getUrl”