长按,从WebView保存图像

时间:2016-10-17 18:04:44

标签: android image webview download long-press

需要帮助

我试图通过长按照片从webview下载图片, 当我用吐司信息测试长按动作时,它起作用了

但它没有下载。

 private View.OnLongClickListener listener=new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            mWebView.setDownloadListener(new DownloadListener() {

                @TargetApi(Build.VERSION_CODES.HONEYCOMB)
                public void onDownloadStart(String url, String userAgent,
                                            String contentDisposition, String mimetype,
                                            long contentLength) {
                    DownloadManager.Request request = new DownloadManager.Request(
                            Uri.parse(url));

                    request.allowScanningByMediaScanner();
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Name of your downloadble file goes here, example: Keerthi");
                    DownloadManager dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
                    dm.enqueue(request);
                    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); //This is important!
                    intent.addCategory(Intent.CATEGORY_OPENABLE); //CATEGORY.OPENABLE
                    intent.setType("*/*");//any application,any extension
                    Toast.makeText(getContext(), "Downloading File", //To notify the Client that the file is being downloaded
                            Toast.LENGTH_LONG).show();

                }
            });
            return true;
        }
    };

5 个答案:

答案 0 :(得分:1)

您需要注册WebView以获取上下文菜单。 在yout activity registerForContextMenu(webView);

并覆盖后显示的onCreateContextMenu方法

  @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        final WebView.HitTestResult result = browser.getHitTestResult();
        MenuItem.OnMenuItemClickListener handler = new MenuItem.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                // handle on context menu click
                return true;
            }
        };

        if (result.getType() == WebView.HitTestResult.IMAGE_TYPE ||
                result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {

            menu.setHeaderTitle(result.getExtra());
            menu.add(0, 666, 0, "Save Image").setOnMenuItemClickListener(handler);
        }
    }

希望这会对你有所帮助

答案 1 :(得分:1)

首先,您必须创建一个上下文菜单。

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
                                ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.context_menu, menu);
}

然后实施onContextItemSelected()

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    switch (item.getItemId()) {
        case R.id.save:
            editNote(info.id);
            return true;
        case R.id.share:
            deleteNote(info.id);
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}

有关详情:context-menu

之后,您需要实施下载。 看到这两个答案:

Neil Traft's answer

save-images-from-website

希望这些对你所做的事情有益。

答案 2 :(得分:1)

Alexander和Aashish的答案都很棒。 但是,这是tutorial I recently found的完整活动。它将一切都放在一个清晰的环境中。

package com.android_examples.saveimagefromwebview_android_examplescom;
import android.app.DownloadManager;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.URLUtil;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    WebView webView;
    String HTTP_URL = "https://www.google.com" ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = (WebView)findViewById(R.id.WebView1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());

        //Register the WebView to be able to take display a menu...
        //You'll need this menu to choose an action on long press
        registerForContextMenu(webView);
        webView.loadUrl(HTTP_URL);
    }

    @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.setHeaderTitle("Download Image From Below");

            contextMenu.add(0, 1, 0, "Save - Download Image")
                    .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem menuItem) {

                            String DownloadImageURL = webViewHitTestResult.getExtra();

                            if(URLUtil.isValidUrl(DownloadImageURL)){

                                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadImageURL));
                                request.allowScanningByMediaScanner();


                                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                                downloadManager.enqueue(request);

                                Toast.makeText(MainActivity.this,"Image Downloaded Successfully.",Toast.LENGTH_LONG).show();
                            }
                            else {
                                Toast.makeText(MainActivity.this,"Sorry.. Something Went Wrong.",Toast.LENGTH_LONG).show();
                            }
                            return false;
                        }
                    });
        }
    }
}

答案 3 :(得分:0)

尝试遵循代码,这对我有用。

    webview.setOnLongClickListener(v->{
                WebView.HitTestResult result = ((WebView)v).getHitTestResult();
                if (null == result)
                    return false;
                int type = result.getType();
                if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
                    return false;
                }
                Log.i(TAG,"check current type:"+type);
                if (WebView.HitTestResult.IMAGE_TYPE == type) {
//result.getExtra() will get image data which encode by base64,format like 'data:image/png;base64,1Pns23s....' or url like http://xxxx/xx.jpg
                    Log.i(TAG,"long click image:"+result.getExtra());
                }
                return true;
            });

答案 4 :(得分:0)

webView.setOnLongClickListener(new View.OnLongClickListener() {

                @Override public boolean onLongClick(View v) 
                {

                    WebView webView = (WebView) v;
                    final WebView.HitTestResult hr = webView.getHitTestResult();

                                     int type = hr.getType();
                    if (type == hr.IMAGE_TYPE || type == hr.SRC_IMAGE_ANCHOR_TYPE) {                        
                  String imageUrl = hr.getExtra();

                                Toast.makeText(getApplicationContext(), "pesquisa ma web..!!!"+imageUrl,                                        Toast.LENGTH_LONG).show(); 
                        return true;
                    }


            return false  ;} });