我创建了一个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;
                    }
                });

最佳答案

这应该将图像保存在下载文件夹中。如果没有保存在那里,您可以对代码进行一些更改

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"/>


还可以通过编程方式授予权限,现在您可以将此图像保存在要指定的任何位置。

09-10 07:06
查看更多