为 WebView 注册配置
registerForContextMenu(webView);
添加保存方法
@Override
public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo){
super.onCreateContextMenu(contextMenu, view, contextMenuInfo);
final WebView.HitTestResult webViewHitTestResult = webView.getHitTestResult();
if (webViewHitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE || webViewHitTestResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
contextMenu.add(0, 1, 0, "保存图片到本地")
.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
String DownloadImageURL = webViewHitTestResult.getExtra();
String fileName = URLUtil.guessFileName(DownloadImageURL, null, null);
if(URLUtil.isValidUrl(DownloadImageURL)){
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadImageURL));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,fileName);
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadManager.enqueue(request);
Toast.makeText(MainActivity.this,"保存成功",Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MainActivity.this,"保存失败",Toast.LENGTH_LONG).show();
}
return false;
}
});
}
}
网友评论