Lorem ipsum dolor sit amet, consectetur adipiscing elit. Test link

long press to download webview android

long press to download webview android


public class MyWebViewClient extends WebViewClient {

    private Context mContext;

    public MyWebViewClient(Context context) {
        mContext = context;
    }

    @Override
    public void onLongPress(MotionEvent event) {
        HitTestResult result = getHitTestResult();
        if (result.getType() == HitTestResult.IMAGE_TYPE) {
            showDownloadDialog(result.getExtra());
        }
    }

    private void showDownloadDialog(final String url) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("Download image?");
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                downloadImage(url);
            }
        });
        builder.setNegativeButton("No", null);
        builder.show();
    }

    private void downloadImage(String url) {
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "myimage.jpg");
        DownloadManager downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        downloadManager.enqueue(request);
    }

}

        

Post a Comment