Search in sources :

Example 1 with DownloadListener

use of android.webkit.DownloadListener in project FastDev4Android by jiangqqlmj.

the class HTML5WebViewCustomAD method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mWebView = new HTML5CustomWebView(this, HTML5WebViewCustomAD.this, title, ad_url);
    mWebView.setDownloadListener(new DownloadListener() {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    });
    //准备javascript注入
    mWebView.addJavascriptInterface(new Js2JavaInterface(), "Js2JavaInterface");
    if (savedInstanceState != null) {
        mWebView.restoreState(savedInstanceState);
    } else {
        if (ad_url != null) {
            mWebView.loadUrl(ad_url);
        }
    }
    setContentView(mWebView.getLayout());
}
Also used : DownloadListener(android.webkit.DownloadListener) Intent(android.content.Intent) Uri(android.net.Uri)

Example 2 with DownloadListener

use of android.webkit.DownloadListener in project 9GAG by Mixiaoxiao.

the class MxxBrowserActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    // setmProgressBarIndeterminateVisibility(false);
    getActionBar().setDisplayShowHomeEnabled(false);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    // MxxSystemBarTintUtil.setSystemBarTintColor(this);
    setContentView(R.layout.mxx_common_activity_browser);
    initPadding();
    // mActionBar = getActionBar();
    // mActionBar.setTitle("");
    // mActionBar.setDisplayHomeAsUpEnabled(true);
    setActionBarTitle("");
    View.OnClickListener toolbar_listener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch(v.getId()) {
                case R.id.mxx_common_activity_browser_toolbar_btn_back:
                    if (webView.canGoBack()) {
                        webView.goBack();
                    }
                    break;
                case R.id.mxx_common_activity_browser_toolbar_btn_forward:
                    if (webView.canGoForward()) {
                        webView.goForward();
                    }
                    break;
                case R.id.mxx_common_activity_browser_toolbar_btn_refresh:
                    webView.reload();
                    break;
                default:
                    break;
            }
        }
    };
    webView = (WebView) this.findViewById(R.id.mxx_common_activity_browser_webview);
    mProgressBar = (ProgressBar) findViewById(R.id.mxx_common_activity_browser_progressbar);
    mBtnBack = (ImageButton) this.findViewById(R.id.mxx_common_activity_browser_toolbar_btn_back);
    mBtnForward = (ImageButton) this.findViewById(R.id.mxx_common_activity_browser_toolbar_btn_forward);
    mBtnRefresh = (ImageButton) this.findViewById(R.id.mxx_common_activity_browser_toolbar_btn_refresh);
    mBtnBack.setEnabled(false);
    mBtnForward.setEnabled(false);
    // mBtnMenu = (ImageButton) this
    // .findViewById(R.id.mxx_common_activity_browser_toolbar_btn_menu);
    // mBtnClose = (ImageButton) this
    // .findViewById(R.id.mxx_common_activity_browser_toolbar_btn_close);
    mBtnBack.setOnClickListener(toolbar_listener);
    mBtnForward.setOnClickListener(toolbar_listener);
    // mBtnMenu.setOnClickListener(toolbar_listener);
    // mBtnClose.setOnClickListener(toolbar_listener);
    mBtnRefresh.setOnClickListener(toolbar_listener);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setSupportMultipleWindows(true);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setSupportZoom(true);
    // webView.getSettings().setUseWideViewPort(true);
    // webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setDefaultZoom(ZoomDensity.MEDIUM);
    webView.getSettings().setCacheMode(WebSettings.LOAD_NORMAL);
    webView.setClipToPadding(false);
    // webView.setFitsSystemWindows(true);
    webView.setDownloadListener(new DownloadListener() {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            try {
                // mActionBar.setTitle("下载");
                setActionBarTitle("download");
                Uri uri = Uri.parse(url);
                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(Intent.createChooser(it, "下载"));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                MxxToastUtil.showToast(MxxBrowserActivity.this, "没有应用可执行此操作");
            }
        }
    });
    // webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
    webView.setWebViewClient(new WebViewClient() {

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // mUrlTitle.setText("鍔犺浇涓?..");
            // mActionBar.setTitle("loading...");
            setActionBarTitle("loading...");
            mProgressBar.setVisibility(View.VISIBLE);
        // mPage_title.setVisibility(View.INVISIBLE);
        }

        public void onPageFinished(WebView view, String url) {
            mProgressBar.setVisibility(View.INVISIBLE);
            mBtnBack.setEnabled(view.canGoBack());
            mBtnForward.setEnabled(view.canGoForward());
        // mActionBar.setTitle(url);
        // mUrlTitle.setText(url);
        }
    });
    webView.setWebChromeClient(new WebChromeClient() {

        public void onProgressChanged(WebView view, int newProgress) {
            // mmProgressBar.setProgress(newProgress);
            // 璁剧疆杩涘害鐨勯暱搴︼紝0 <= progress <= 10000.
            // setProgress(newProgress * 100);
            mProgressBar.setProgress(newProgress);
        }

        public void onReceivedIcon(WebView view, Bitmap icon) {
        // mFavor_icon.setImageBitmap(icon);
        // mActionBar.setLogo(new BitmapDrawable(getResources(),icon));
        }

        public void onReceivedTitle(WebView view, String title) {
            // mUrlTitle.setText(title);
            // mActionBar.setTitle(title);
            setActionBarTitle(title);
        }
    });
    Intent intent = getIntent();
    if (intent.hasExtra(extra_string_name)) {
        String urlString = intent.getStringExtra(extra_string_name);
        // webView.loadDataWithBaseURL(null, htmlString, "text/html",
        // "utf-8", null);
        webView.loadUrl(urlString);
    } else {
        // UiUtils.showToast(this, "锟斤拷莶锟斤拷锟饺笔?);
        finish();
    }
}
Also used : OnClickListener(android.view.View.OnClickListener) Intent(android.content.Intent) SpannableString(android.text.SpannableString) View(android.view.View) WebView(android.webkit.WebView) Uri(android.net.Uri) Bitmap(android.graphics.Bitmap) DownloadListener(android.webkit.DownloadListener) WebChromeClient(android.webkit.WebChromeClient) OnClickListener(android.view.View.OnClickListener) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient)

Example 3 with DownloadListener

use of android.webkit.DownloadListener in project openremote by openremote.

the class MainActivity method initializeWebView.

protected void initializeWebView() {
    LOG.fine("Initializing web view");
    final WebAppInterface webAppInterface = new WebAppInterface(this);
    webView.addJavascriptInterface(webAppInterface, "MobileInterface");
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    webSettings.setDomStorageEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webView.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            return true;
        }
    });
    webView.setLongClickable(false);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            // TODO should we ignore images?
            if (request.getUrl().getLastPathSegment() != null && (request.getUrl().getLastPathSegment().endsWith("png") || request.getUrl().getLastPathSegment().endsWith("jpg") || request.getUrl().getLastPathSegment().endsWith("ico")))
                return;
            // invalid token. The web app will then start a new login.
            if (request.getUrl().getLastPathSegment() != null && request.getUrl().getLastPathSegment().equals("token") && request.getMethod().equals("POST") && errorResponse.getStatusCode() == 400) {
                webAppInterface.tokenService.clearToken();
                return;
            }
            LOG.warning("Error requesting '" + request.getUrl() + "', response code: " + errorResponse.getStatusCode());
            errorViewHolder.show(R.string.httpError, R.string.httpErrorExplain, true, true);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            if (Boolean.parseBoolean(getString(R.string.SSL_IGNORE))) {
                LOG.fine("Ignoring SSL certificate error: " + error.getPrimaryError());
                // Ignore SSL certificate errors
                handler.proceed();
            } else {
                LOG.severe("SSL error: " + error.getPrimaryError());
                LOG.severe("SSL certificate: " + error.getCertificate());
                errorViewHolder.show(R.string.httpError, R.string.httpErrorExplain, true, true);
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            // TODO should we ignore images?
            if (request.getUrl().getLastPathSegment() != null && (request.getUrl().getLastPathSegment().endsWith("png") || request.getUrl().getLastPathSegment().endsWith("jpg") || request.getUrl().getLastPathSegment().endsWith("ico")))
                return;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // Remote debugging sessions from Chrome trigger "ERR_CACHE_MISS" that don't hurt, but we should not redirect the view
                if (isRemoteDebuggingEnabled() && error.getErrorCode() == ERROR_UNKNOWN) {
                    return;
                }
                // Remote debugging session from Chrome wants to load about:blank and then fails with "ERROR_UNSUPPORTED_SCHEME", ignore
                if (request.getUrl().toString().equals("about:blank") && error.getErrorCode() == ERROR_UNSUPPORTED_SCHEME) {
                    return;
                }
                LOG.warning("Error requesting '" + request.getUrl() + "': " + error.getErrorCode());
            }
            errorViewHolder.show(R.string.fatalError, R.string.fatalErrorExplain, false, true);
        }
    });
    webView.setWebChromeClient(new WebChromeClient() {

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            String msg = "WebApp console (" + consoleMessage.sourceId() + ":" + consoleMessage.lineNumber() + "): " + consoleMessage.message();
            switch(consoleMessage.messageLevel()) {
                case DEBUG:
                case TIP:
                    LOG.fine(msg);
                    break;
                case LOG:
                    LOG.info(msg);
                    break;
                default:
                    LOG.severe(msg);
            }
            return true;
        }
    });
    webView.setDownloadListener(new DownloadListener() {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            String writePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
            if (ContextCompat.checkSelfPermission(context, writePermission) != PackageManager.PERMISSION_GRANTED) {
                // Location permission has not been granted yet, request it.
                ActivityCompat.requestPermissions((MainActivity) context, new String[] { writePermission }, WRITE_PERMISSION_REQUEST);
            } else {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                request.setMimeType(mimetype);
                // ------------------------COOKIE!!------------------------
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie", cookies);
                // ------------------------COOKIE!!------------------------
                request.addRequestHeader("User-Agent", userAgent);
                request.setDescription("Downloading file...");
                request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimetype));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimetype));
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                if (dm != null) {
                    Toast.makeText(getApplicationContext(), R.string.downloading_file, Toast.LENGTH_LONG).show();
                    dm.enqueue(request);
                } else {
                    Toast.makeText(getApplicationContext(), R.string.error_downloading, Toast.LENGTH_LONG).show();
                }
            }
        }
    });
}
Also used : SslErrorHandler(android.webkit.SslErrorHandler) WebResourceRequest(android.webkit.WebResourceRequest) SslError(android.net.http.SslError) WebResourceRequest(android.webkit.WebResourceRequest) View(android.view.View) WebView(android.webkit.WebView) TextView(android.widget.TextView) DownloadManager(android.app.DownloadManager) ConsoleMessage(android.webkit.ConsoleMessage) WebResourceResponse(android.webkit.WebResourceResponse) DownloadListener(android.webkit.DownloadListener) WebSettings(android.webkit.WebSettings) WebChromeClient(android.webkit.WebChromeClient) WebResourceError(android.webkit.WebResourceError) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient)

Aggregations

DownloadListener (android.webkit.DownloadListener)3 Intent (android.content.Intent)2 Uri (android.net.Uri)2 View (android.view.View)2 WebChromeClient (android.webkit.WebChromeClient)2 WebView (android.webkit.WebView)2 WebViewClient (android.webkit.WebViewClient)2 DownloadManager (android.app.DownloadManager)1 Bitmap (android.graphics.Bitmap)1 SslError (android.net.http.SslError)1 SpannableString (android.text.SpannableString)1 OnClickListener (android.view.View.OnClickListener)1 ConsoleMessage (android.webkit.ConsoleMessage)1 SslErrorHandler (android.webkit.SslErrorHandler)1 WebResourceError (android.webkit.WebResourceError)1 WebResourceRequest (android.webkit.WebResourceRequest)1 WebResourceResponse (android.webkit.WebResourceResponse)1 WebSettings (android.webkit.WebSettings)1 TextView (android.widget.TextView)1