我创建了一个webview Android应用程序并添加了“长按以保存图像”选项 代码运行没有问题,它也下载图像,我可以从通知面板打开下载的图像,但我不知道它保存在哪里。我搜索了我的存储的每个文件夹,但我找不到该文件。 这是我的“上下文菜单”的代码
//To save image from web view
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// Get the web view hit test result
final WebView.HitTestResult result = myWebView.getHitTestResult();
/*
WebView.HitTestResult
IMAGE_TYPE
HitTestResult for hitting an HTML::img tag.
SRC_IMAGE_ANCHOR_TYPE
HitTestResult for hitting a HTML::a tag with src=http + HTML::img.
*/
// If user long press on an image
if (result.getType() == WebView.HitTestResult.IMAGE_TYPE ||
result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
// Set the title for context menu
menu.setHeaderTitle("CONTEXT MENU");
// Add an item to the menu
menu.add(0, 1, 0, "Save Image")
.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
// Get the image url
String imgUrl = result.getExtra();
// If this is an image url then download it
if (URLUtil.isValidUrl(imgUrl)) {
// Initialize a new download request
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(imgUrl));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadManager.enqueue(request);
Toast.makeText(myContext, "image saved.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(myContext, "Invalid image url.", Toast.LENGTH_SHORT).show();
}
return false;
}
});
答案 0 :(得分:0)
这应该将图像保存在下载文件夹中。如果没有保存,您可以在代码中进行一些更改
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, //Download folder
URLUtil.guessFileName(DownloadImageURL, null, null)); //Name of file
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
您需要在清单文件中提供存储权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
以编程方式授予权限,现在您可以将此图片保存到您想要指定的位置。