1、给webVeiw注册长按事件
val webview=findViewById(R.id.web_view)
registerForContextMenu(webView)
2、捕获WebView组件中长按事件,重写 Activity子类的onCreateContextMenu函数
override fun onCreateContextMenu(menu: ContextMenu, view: View, menuInfo: ContextMenu.ContextMenuInfo?) {
webView!!.hitTestResult?.let {
when (it.type) {//判断所长按的类型,如果是图片->
WebView.HitTestResult.IMAGE_TYPE,
WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE -> {
Logger.d("viewtype",it.type.toString())
menu.setHeaderTitle("Image Options")
menu.add(0, 1, 0, "Download")
}
else -> Logger.d("App does not yet handle target type: ${it.type}")
}
}
super.onCreateContextMenu(menu, view, menuInfo)
Logger.d("oncreatemune","长按了")
}
3、重写onContextItemSelected函数,当2中add的菜单项被点击时调用,因为只添加了一个菜单项,所有下面没有对点击的哪一项进行判断
override fun onContextItemSelected(item: MenuItem): Boolean {
webView!!.hitTestResult?.let {
when (it.type) {
WebView.HitTestResult.IMAGE_TYPE,
WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE -> {//如果是图片就调用自己写的downloadFile()函数下载图片
val path=Environment.getExternalStorageDirectory().getPath()+"/DCIM"
downloadFile(imgSrc!!,path)
}
else -> Logger.d("App does not yet handle target type: ${it.type}")
}
}
return super.onContextItemSelected(item)
}
4、downloadFile函数:参数分别为图片的下载地址和要存储到的路径
使用DownloadManager进行下载
private fun downloadFile(url:String,path:String) {
val uri = Uri.parse(url)
val guessedFileName = URLUtil.guessFileName(url, null, null)
val request = DownloadManager.Request(uri).apply {
allowScanningByMediaScanner()
setDestinationInExternalPublicDir(path, guessedFileName)
setNotificationVisibility(VISIBILITY_VISIBLE_NOTIFY_COMPLETED)//通知栏的下载条,VISIBILITY_VISIBLE_NOTIFY_COMPLETED是个常量,表示在下载过程中通知栏会一直显示该下载的Notification
}
val manager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
manager.enqueue(request)
//下面的代码是发送广播,刷新Media库更新相册
val contentUri = Uri.fromFile(File(path+File.separator+guessedFileName))
val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,contentUri)
sendBroadcast(mediaScanIntent)
}
5、注意事项
(1)onCreateContextMenu不要与setOnLongClickListener同时使用
(2)设置图片的储存路径时,有些路径手机的系统不会识别,我这里设置的根目录+/DCIM,我在用小米手机进行测试时,发现生成的相册会被屏蔽,需要在相册设置中打开“显示被屏蔽的相册”
网友评论