Search in sources :

Example 11 with WebResourceResponse

use of android.webkit.WebResourceResponse in project SwipeToLoadLayout by Aspsine.

the class TwitterWebViewFragment method onViewCreated.

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    swipeToLoadLayout = (SwipeToLoadLayout) view.findViewById(R.id.swipeToLoadLayout);
    webView = (WebView) view.findViewById(R.id.swipe_target);
    swipeToLoadLayout.setOnRefreshListener(this);
    swipeToLoadLayout.setOnLoadMoreListener(this);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            swipeToLoadLayout.setRefreshing(false);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            swipeToLoadLayout.setRefreshing(false);
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
            swipeToLoadLayout.setRefreshing(false);
        }
    });
}
Also used : WebResourceRequest(android.webkit.WebResourceRequest) WebResourceResponse(android.webkit.WebResourceResponse) WebResourceError(android.webkit.WebResourceError) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient)

Example 12 with WebResourceResponse

use of android.webkit.WebResourceResponse 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)

Example 13 with WebResourceResponse

use of android.webkit.WebResourceResponse in project platform_packages_apps_PdfViewer by CopperheadOS.

the class PdfViewer method onCreate.

@Override
@SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);
    mWebView = findViewById(R.id.webview);
    final WebSettings settings = mWebView.getSettings();
    settings.setAllowContentAccess(false);
    settings.setAllowFileAccess(false);
    settings.setAllowUniversalAccessFromFileURLs(true);
    settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    settings.setJavaScriptEnabled(true);
    disableSaveFormData(settings);
    CookieManager.getInstance().setAcceptCookie(false);
    mChannel = new Channel();
    mWebView.addJavascriptInterface(mChannel, "channel");
    mWebView.setWebViewClient(new WebViewClient() {

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            if ("GET".equals(request.getMethod()) && "https://localhost/placeholder.pdf".equals(request.getUrl().toString())) {
                return new WebResourceResponse("application/pdf", null, mInputStream);
            }
            return null;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            mDocumentState = STATE_LOADED;
            invalidateOptionsMenu();
        }
    });
    mTextView = new TextView(this);
    mTextView.setBackgroundColor(Color.DKGRAY);
    mTextView.setTextColor(ColorStateList.valueOf(Color.WHITE));
    mTextView.setTextSize(18);
    mTextView.setPadding(PADDING, 0, PADDING, 0);
    final Intent intent = getIntent();
    if (Intent.ACTION_VIEW.equals(intent.getAction())) {
        if (!"application/pdf".equals(intent.getType())) {
            Log.e(TAG, "invalid mime type");
            finish();
            return;
        }
        mUri = intent.getData();
        mPage = 1;
    }
    if (savedInstanceState != null) {
        mUri = savedInstanceState.getParcelable(STATE_URI);
        mPage = savedInstanceState.getInt(STATE_PAGE);
        mZoomLevel = savedInstanceState.getInt(STATE_ZOOM_LEVEL);
        mDocumentProperties = savedInstanceState.getCharSequenceArrayList(STATE_PROPERTIES);
    }
    if (mUri != null) {
        loadPdf();
    }
}
Also used : WebResourceRequest(android.webkit.WebResourceRequest) WebResourceResponse(android.webkit.WebResourceResponse) WebSettings(android.webkit.WebSettings) TextView(android.widget.TextView) Intent(android.content.Intent) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient) SuppressLint(android.annotation.SuppressLint)

Aggregations

WebResourceResponse (android.webkit.WebResourceResponse)13 WebResourceRequest (android.webkit.WebResourceRequest)6 WebView (android.webkit.WebView)6 WebViewClient (android.webkit.WebViewClient)6 IOException (java.io.IOException)6 WebChromeClient (android.webkit.WebChromeClient)4 WebSettings (android.webkit.WebSettings)4 SuppressLint (android.annotation.SuppressLint)3 Uri (android.net.Uri)3 WebResourceError (android.webkit.WebResourceError)3 TargetApi (android.annotation.TargetApi)2 Bitmap (android.graphics.Bitmap)2 SslError (android.net.http.SslError)2 ConsoleMessage (android.webkit.ConsoleMessage)2 SslErrorHandler (android.webkit.SslErrorHandler)2 TextView (android.widget.TextView)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 FileNotFoundException (java.io.FileNotFoundException)2 InputStream (java.io.InputStream)2 HttpURLConnection (java.net.HttpURLConnection)2