Example usage for android.webkit WebViewClient WebViewClient

List of usage examples for android.webkit WebViewClient WebViewClient

Introduction

In this page you can find the example usage for android.webkit WebViewClient WebViewClient.

Prototype

WebViewClient

Source Link

Usage

From source file:thiru.in.basicauthwebview.ShowWebViewActivity.java

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

    // Initialize the Cookie Manager
    CookieSyncManager.createInstance(this);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);

    String url = "http://auth.thiru.in/";
    // Call the REST Service to Authenticate
    // This is sample app, the app can have a login form, accept input, encode the
    // id and passowrd using Base64 for Validating
    AsyncTask<String, Void, CookieStore> cookieStoreTask = new Authenticate(this).execute(url + "app-auth",
            "ZGVtbzpkZW1v"); //Base64 Encoded for demo:demo

    try {/*from ww w  .j  a  va  2s .  c  o  m*/
        cookieManager.removeAllCookie();
        CookieStore cookieStore = cookieStoreTask.get();
        List<Cookie> cookies = cookieStore.getCookies();
        // If the User id and password is wrong, the cookie store will not have any cookies
        // And the page will display 403 Access Denied
        for (Cookie cookie : cookies) {
            Log.i("Cookie", cookie.getName() + " ==> " + cookie.getValue());
            // Add the REST Service Cookie Responses to Cookie Manager to make it
            // Available for the WebViewClient
            cookieManager.setCookie(url, cookie.getName() + "=" + cookie.getValue());
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

    mWebView = (WebView) findViewById(R.id.activity_main_webview);
    mWebView.setWebViewClient(new WebViewClient());
    mWebView.loadUrl(url);
}

From source file:org.freespanish.diccionario.fragments.search.SearchFragment.java

@Override
public void setupViews() {
    this.searchPresenter = new SearchPresenterImpl(this);
    this.searchWebview.setWebViewClient(new WebViewClient() {

        void handleLink(String url) {
            url = url.substring(url.lastIndexOf("/") + 1, url.length());
            SearchFragment.this.searchPresenter.prepareDefinition(url, true);
        }//w  ww. ja  v a 2  s.  c  o m

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            setProgressBarVisibility(View.GONE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains("fetch"))
                handleLink(url);
            return true;
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            if (request.getUrl().toString().contains("fetch"))
                handleLink(request.getUrl().toString());
            return true;
        }
    });

    if (pendingWordToSearch != null) {
        this.searchInfoLayout.setVisibility(View.GONE);
        onWordSearched(pendingWordToSearch);
        pendingWordToSearch = null;
    }
}

From source file:com.commonsware.android.print.MainActivity.java

private WebView prepPrintWebView(final String name) {
    WebView result = getWebView();/* ww  w  . j  a v  a 2s  .c o  m*/

    result.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            print(name, view.createPrintDocumentAdapter(), new PrintAttributes.Builder().build());
        }
    });

    return (result);
}

From source file:justforcommunity.radiocom.activities.ContentDetail.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_contentdetail);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);//from   w  w  w.j a v a2s .com
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });

    prefs = this.getSharedPreferences(GlobalValues.prefName, Context.MODE_PRIVATE);
    edit = prefs.edit();

    detail_web = (WebView) findViewById(R.id.detail_web);

    content = getIntent().getStringExtra(GlobalValues.EXTRA_CONTENT);

    detail_web.setBackgroundColor(Color.WHITE);

    title = getIntent().getStringExtra(GlobalValues.EXTRA_TITLE);

    getSupportActionBar().setTitle(title);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }

    try {
        content = content.replaceAll("style=\".+?\"", "");
    } catch (Exception e) {

    }

    String fontscript = "";
    String script = "<style type='text/css' >p{width:100%;}img{width:100%;height:auto;-webkit-transform: translate3d(0px,0px,0px);}a,h1,h2,h3,h4,h5,h6{color:"
            + GlobalValues.colorHTML
            + ";}div,p,span,a {max-width: 100%;}iframe{width:100%;height:auto;}</style>";

    detail_web.loadDataWithBaseURL(
            GlobalValues.baseURLWEB, "<html><head>" + fontscript + script
                    + "</head><body style=\"font-family:HelveticaNeue-Light; \">" + content + "</body></html>",
            "text/html", "utf-8", "");
    detail_web.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if ((url != null && url.startsWith("http://")) || (url != null && url.startsWith("https://"))) {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } else {
                return false;
            }

        }

        public void onPageFinished(WebView view, String url) {
        }

        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        }
    });
    detail_web.getSettings().setDomStorageEnabled(true);
    detail_web.getSettings().setJavaScriptEnabled(true);

    App appliaction = (App) getApplication();
    Tracker mTracker = appliaction.getDefaultTracker();
    mTracker.setScreenName(getString(R.string.content_activity));
    mTracker.send(new HitBuilders.ScreenViewBuilder().build());

}

From source file:org.noise_planet.noisecapture.MapFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (view == null) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_measurement_map, container, false);
        leaflet = (WebView) view.findViewById(R.id.measurement_webmapview);
        leaflet.clearCache(true);/*  www  .  j  av a  2s .c  om*/
        leaflet.clearHistory();
        WebSettings webSettings = leaflet.getSettings();
        webSettings.setJavaScriptEnabled(true);
        WebSettings settings = leaflet.getSettings();
        settings.setAppCachePath(new File(getContext().getCacheDir(), "webview").getPath());
        settings.setAppCacheEnabled(true);
        leaflet.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                pageLoaded.set(true);
                if (mapFragmentAvailableListener != null) {
                    mapFragmentAvailableListener.onPageLoaded(MapFragment.this);
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(browserIntent);
                return true;
            }
        });
        if (mapFragmentAvailableListener != null) {
            mapFragmentAvailableListener.onMapFragmentAvailable(this);
        }
    }
    return view;
}

From source file:in.rab.bildkort.ImageFragment.java

@SuppressLint("SetJavaScriptEnabled")
@Override//from  w  w w.  j a  v  a  2 s.  c o m
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    mWebView = (WebView) getView().findViewById(R.id.webView);
    final ProgressBar progress = (ProgressBar) getView().findViewById(R.id.image_progress);
    mWebView.setWebChromeClient(new WebChromeClient());
    final WebSettings settings = mWebView.getSettings();

    settings.setBuiltInZoomControls(true);
    settings.setDisplayZoomControls(false);
    settings.setJavaScriptEnabled(true);

    // We replace the src urls in imagepicker.js::init(), so don't load
    // images twice.
    settings.setBlockNetworkImage(true);

    mWebView.setInitialScale(100);

    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            if (Objects.equals(url, GSTATIC_SERVER)) {
                settings.setBlockNetworkImage(false);

                progress.setVisibility(View.GONE);
                mWebView.setVisibility(View.VISIBLE);
            } else {
                view.loadUrl("javascript:" + getImagePickerJs() + "getPickerHtml();");
            }
        }
    });

    mWebView.addJavascriptInterface(new WcmJsObject(), "wcm");
    mWebView.loadUrl("https://www.google.se/search?tbm=isch&q=" + getWord());
}

From source file:com.qiscus.sdk.ui.QiscusAccountLinkingActivity.java

@SuppressLint("SetJavaScriptEnabled")
private void setupWebView() {
    webView.setWebViewClient(new WebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setAppCacheEnabled(true);
    webView.setWebViewClient(new QiscusWebViewClient());
    webView.setWebChromeClient(new QiscusChromeClient());
}

From source file:com.activiti.android.app.fragments.HelpDialogFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.app_webview, container, false);

    getToolbar().setVisibility(View.GONE);

    webView = (WebView) v.findViewById(R.id.webview);
    webView.getSettings().setJavaScriptEnabled(true);
    emptyView = v.findViewById(R.id.empty);
    emptyTextView = (TextView) v.findViewById(R.id.empty_text);
    emptyTextView.setText(Html.fromHtml(getString(R.string.error_offline)));

    final Activity activity = getActivity();

    defaultUrl = activity.getString(R.string.help_user_guide_default_url);

    webView.setWebViewClient(new WebViewClient() {
        boolean hasError = false;

        @Override/*from  ww w.  j a v a 2 s.co m*/
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            hasError = false;
            getActivity().setProgressBarIndeterminateVisibility(true);
            refreshIcon.setVisible(false);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);

            // We redirect to default EN documentation if locale docs are
            // not available.
            if ((errorCode == ERROR_FILE_NOT_FOUND || errorCode == ERROR_HOST_LOOKUP) && !isDefault
                    && failingUrl.equals(rootUrl)) {
                hasError = true;
                view.loadUrl(defaultUrl);
                view.setVisibility(View.GONE);
            } else if (!ConnectivityUtils.hasInternetAvailable(getActivity())) {
                view.setVisibility(View.GONE);
                emptyView.setVisibility(View.VISIBLE);
                hasError = true;
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (hasError) {
                view.setVisibility(View.GONE);
            } else {
                view.setVisibility(View.VISIBLE);
            }

            if (getActivity() != null) {
                getActivity().setProgressBarIndeterminateVisibility(false);
                refreshIcon.setVisible(true);
            }
        }

        public void onFormResubmission(WebView view, Message dontResend, Message resend) {
            resend.sendToTarget();
        }

    });

    webView.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    if (webView.canGoBack()) {
                        webView.goBack();
                        return true;
                    }
                    break;
                }
            }
            return false;
        }
    });

    rootUrl = getUrl(activity);
    webView.loadUrl(rootUrl);

    return v;
}

From source file:org.alfresco.mobile.android.application.fragments.help.HelpDialogFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.app_webview, container, false);

    webView = (WebView) v.findViewById(org.alfresco.mobile.android.foundation.R.id.webview);
    webView.getSettings().setJavaScriptEnabled(true);
    emptyView = v.findViewById(org.alfresco.mobile.android.foundation.R.id.empty);
    emptyTextView = (TextView) v.findViewById(org.alfresco.mobile.android.foundation.R.id.empty_text);
    emptyTextView.setText(Html.fromHtml(getString(R.string.error_offline)));

    final FragmentActivity activity = getActivity();

    defaultUrl = activity.getString(R.string.help_user_guide_default_url);

    webView.setWebViewClient(new WebViewClient() {
        boolean hasError = false;

        @Override//ww w .java  2  s . com
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            hasError = false;
            displayProgress(true);
            if (refreshIcon != null) {
                refreshIcon.setVisible(false);
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);

            // We redirect to default EN documentation if locale docs are
            // not available.
            if ((errorCode == ERROR_FILE_NOT_FOUND || errorCode == ERROR_HOST_LOOKUP) && !isDefault
                    && failingUrl.equals(rootUrl)) {
                hasError = true;
                view.loadUrl(defaultUrl);
                view.setVisibility(View.GONE);
            } else if (!ConnectivityUtils.hasInternetAvailable(getActivity())) {
                view.setVisibility(View.GONE);
                emptyView.setVisibility(View.VISIBLE);
                hasError = true;
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (getActivity() == null) {
                return;
            }
            super.onPageFinished(view, url);
            if (hasError) {
                view.setVisibility(View.GONE);
            } else {
                view.setVisibility(View.VISIBLE);
            }
            displayProgress(false);
            if (refreshIcon != null) {
                refreshIcon.setVisible(true);
            }
        }

        public void onFormResubmission(WebView view, Message dontResend, Message resend) {
            resend.sendToTarget();
        }

    });

    webView.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    if (webView.canGoBack()) {
                        webView.goBack();
                        return true;
                    }
                    break;
                }
            }
            return false;
        }
    });

    rootUrl = getUrl(activity);
    webView.loadUrl(rootUrl);

    return v;
}

From source file:com.github.dfa.diaspora_android.activity.ShareActivity.java

@SuppressLint("SetJavaScriptEnabled")
@Override//from   w w w.  j  a v a 2  s  .  c o  m
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main__activity);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    if (toolbar != null) {
        toolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Helpers.isOnline(ShareActivity.this)) {
                    Intent intent = new Intent(ShareActivity.this, MainActivity.class);
                    startActivityForResult(intent, 100);
                    overridePendingTransition(0, 0);
                    finish();
                } else {
                    Snackbar.make(swipeView, R.string.no_internet, Snackbar.LENGTH_LONG).show();
                }
            }
        });
    }
    setTitle(R.string.new_post);

    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
    swipeView.setEnabled(false);

    podDomain = ((App) getApplication()).getSettings().getPodDomain();

    webView = (WebView) findViewById(R.id.webView);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

    WebSettings wSettings = webView.getSettings();
    wSettings.setJavaScriptEnabled(true);
    wSettings.setBuiltInZoomControls(true);

    if (Build.VERSION.SDK_INT >= 21)
        wSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

    /*
     * WebViewClient
     */
    webView.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d(TAG, url);
            if (!url.contains(podDomain)) {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
                return true;
            }
            return false;

        }

        public void onPageFinished(WebView view, String url) {
            Log.i(TAG, "Finished loading URL: " + url);
        }
    });

    /*
     * WebChromeClient
     */
    webView.setWebChromeClient(new WebChromeClient() {

        public void onProgressChanged(WebView wv, int progress) {
            progressBar.setProgress(progress);

            if (progress > 0 && progress <= 60) {
                Helpers.getNotificationCount(wv);
            }

            if (progress > 60) {
                Helpers.applyDiasporaMobileSiteChanges(wv);
            }

            if (progress == 100) {
                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null)
                mFilePathCallback.onReceiveValue(null);

            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Snackbar.make(getWindow().findViewById(R.id.main__layout), "Unable to get image",
                            Snackbar.LENGTH_LONG).show();
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }
    });

    if (savedInstanceState == null) {
        if (Helpers.isOnline(ShareActivity.this)) {
            webView.loadUrl("https://" + podDomain + "/status_messages/new");
        } else {
            Snackbar.make(getWindow().findViewById(R.id.main__layout), R.string.no_internet,
                    Snackbar.LENGTH_LONG).show();
        }
    }

    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if ("text/plain".equals(type)) {
            if (intent.hasExtra(Intent.EXTRA_SUBJECT)) {
                handleSendSubject(intent);
            } else {
                handleSendText(intent);
            }
        } else if (type.startsWith("image/")) {
            // TODO Handle single image being sent -> see manifest
            handleSendImage(intent);
        }
        //} else {
        // Handle other intents, such as being started from the home screen
    }

}