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:gov.whitehouse.ui.fragments.app.ArticleViewerFragment.java

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

    mWebView = (WebView) v.findViewById(R.id.webview);
    mProgressBar = (ProgressBar) v.findViewById(R.id.progress);

    mWebView.getSettings().setJavaScriptEnabled(true);
    // enabling plugins may yield a better result for YouTube videos
    mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);

    mWebView.setWebChromeClient(new WebChromeClient() {
        public boolean onConsoleMessage(ConsoleMessage cm) {
            Log.d(TAG, cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId());
            return true;
        }//from   w w w .ja v a 2 s .  com
    });

    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Log.e(TAG, "Error in WebView: " + failingUrl + "; " + description);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            mProgressBar.setVisibility(View.INVISIBLE);
            mWebView.setVisibility(View.VISIBLE);
            Log.d(TAG, "page finished: " + url);

            if (url.equals(PAGE_TEMPLATE_URL)) {
                view.loadUrl(String.format("javascript:WhiteHouse.loadPage(%s);", mPageInfo.toString()));
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains("youtube.com/")) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;
            }
            return false;
        }
    });

    return v;
}

From source file:de.madvertise.android.sdk.MadvertiseMraidView.java

public MadvertiseMraidView(Context context) {
    super(context);
    setVerticalScrollBarEnabled(false);//from  w  w  w.  j a va 2  s . c  o m
    setHorizontalScrollBarEnabled(false);
    setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    setBackgroundColor(Color.TRANSPARENT);
    WebSettings settings = getSettings();
    settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    settings.setJavaScriptEnabled(true);
    //settings.setPluginsEnabled(true);

    // Initialize the default expand properties.
    DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
    mExpandProperties = new ExpandProperties(metrics.widthPixels, metrics.heightPixels);
    MadvertiseUtil.logMessage(null, Log.INFO,
            "Setting default expandProperties : " + mExpandProperties.toJson().toString());

    // This bridge stays available until this view is destroyed, hence no
    // reloading when displaying new ads is necessary.
    addJavascriptInterface(mBridge, "mraid_bridge");

    setWebViewClient(new WebViewClient() {
        private boolean mError = false;

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {
            post(new Runnable() {
                @Override
                public void run() {
                    if (mListener != null) {
                        mListener.onAdClicked();
                    }
                    final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url),
                            getContext().getApplicationContext(), MadvertiseActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    getContext().startActivity(intent);
                }
            });
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (!url.endsWith("mraid.js") && !mError) {
                MadvertiseUtil.logMessage(null, Log.DEBUG, "Setting mraid to default");
                checkReady();

                // Close button in default size for interstitial ads
                if (mPlacementType == MadvertiseUtil.PLACEMENT_TYPE_INTERSTITIAL) {
                    mCloseButton = addCloseButtonToViewGroup(((ViewGroup) getParent()));
                    mCloseButton.setImageResource(android.R.drawable.ic_menu_close_clear_cancel);
                }
            }
        }

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

    // Comment this in to enable video tag-capability.
    this.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            MadvertiseUtil.logMessage(null, Log.INFO, "showing VideoView");
            super.onShowCustomView(view, callback);
            if (view instanceof FrameLayout) {
                FrameLayout frame = (FrameLayout) view;
                if (frame.getFocusedChild() instanceof VideoView) {
                    mVideo = (VideoView) ((FrameLayout) view).getFocusedChild();
                    frame.removeView(mVideo);
                    ((ViewGroup) getParent()).addView(mVideo);

                    // Will also be called onError
                    mVideo.setOnCompletionListener(new OnCompletionListener() {

                        @Override
                        public void onCompletion(MediaPlayer player) {
                            player.stop();
                        }
                    });

                    mVideo.setOnErrorListener(new OnErrorListener() {

                        @Override
                        public boolean onError(MediaPlayer mp, int what, int extra) {
                            MadvertiseUtil.logMessage(null, Log.WARN, "Error while playing video");

                            if (mListener != null) {
                                mListener.onError(new IOException("Error while playing video"));
                            }

                            // We return false in order to call
                            // onCompletion()
                            return false;
                        }
                    });

                    mVideo.start();
                }
            }
        }

        @Override
        public void onHideCustomView() {
            if (mVideo != null) {
                ((ViewGroup) getParent()).removeView(mVideo);
                if (mVideo.isPlaying()) {
                    mVideo.stopPlayback();
                }
            }
        }
    });
}

From source file:de.geeksfactory.opacclient.frontend.InfoFragment.java

@SuppressWarnings("deprecation")
@SuppressLint("SetJavaScriptEnabled")
@Override/* ww  w  . j  a  va  2  s.  c  o  m*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    view = inflater.inflate(R.layout.fragment_info, container, false);
    app = (OpacClient) getActivity().getApplication();

    setHasOptionsMenu(true);

    load();

    ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    wvInfo = (WebView) view.findViewById(R.id.wvInfo);

    wvInfo.getSettings().setSupportZoom(true);
    wvInfo.getSettings().setJavaScriptEnabled(true);
    wvInfo.getSettings().setAppCacheMaxSize(5 * 1024 * 1024);
    wvInfo.getSettings().setAppCacheEnabled(true);
    wvInfo.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

    wvInfo.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView v, int progress) {
            ProgressBar Pbar = (ProgressBar) view.findViewById(R.id.pbWebProgress);
            if (progress < 100 && Pbar.getVisibility() == View.GONE) {
                Pbar.setVisibility(View.VISIBLE);
            }
            Pbar.setProgress(progress);
            if (progress == 100) {
                Pbar.setVisibility(View.GONE);
            }
        }

    });
    wvInfo.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains(app.getLibrary().getData().optString("webviewcontain", "NOPE"))) {
                return false;
            }
            if (getActivity() == null) {
                return false;
            }
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }

    });

    return view;
}

From source file:org.eyeseetea.malariacare.fragments.MonitorFragment.java

public void reloadWebView(final IWebViewBuilder iWebViewBuilder) {
    initWebView();//ww  w.ja v a  2s.c  o  m
    //onPageFinish load data
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            iWebViewBuilder.addDataToView(webView);
        }
    });
    //Load html
    webView.loadUrl(FILE_ANDROID_ASSET_MONITOR_MONITOR_HTML);
}

From source file:org.microg.gms.auth.login.LoginActivity.java

@SuppressLint("AddJavascriptInterface")
@Override/*w  ww .  ja v  a2s.co m*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    accountType = AuthConstants.DEFAULT_ACCOUNT_TYPE;
    accountManager = AccountManager.get(LoginActivity.this);
    inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    webView = createWebView(this);
    webView.addJavascriptInterface(new JsBridge(), "mm");
    authContent = (ViewGroup) findViewById(R.id.auth_content);
    ((ViewGroup) findViewById(R.id.auth_root)).addView(webView);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            Log.d(TAG, "pageFinished: " + url);
            if ("identifier".equals(Uri.parse(url).getFragment()))
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        webView.setVisibility(VISIBLE);
                    }
                });
            if ("close".equals(Uri.parse(url).getFragment()))
                closeWeb(false);
            if (url.startsWith(PROGRAMMATIC_AUTH_URL))
                closeWeb(true);
        }
    });
    if (getIntent().hasExtra(EXTRA_TOKEN)) {
        if (getIntent().hasExtra(EXTRA_EMAIL)) {
            AccountManager accountManager = AccountManager.get(LoginActivity.this);
            Account account = new Account(getIntent().getStringExtra(EXTRA_EMAIL), accountType);
            accountManager.addAccountExplicitly(account, getIntent().getStringExtra(EXTRA_TOKEN), null);
            retrieveGmsToken(account);
        } else {
            retrieveRtToken(getIntent().getStringExtra(EXTRA_TOKEN));
        }
    } else {
        setMessage(R.string.auth_before_connect);
        setBackButtonText(android.R.string.cancel);
        setNextButtonText(R.string.auth_sign_in);
    }
}

From source file:au.com.wallaceit.reddinator.TabCommentsFragment.java

@SuppressLint({ "SetJavaScriptEnabled", "AddJavascriptInterface" })
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContext = this.getActivity();
    SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
    global = (GlobalObjects) mContext.getApplicationContext();
    final boolean load = getArguments().getBoolean("load");

    // get needed activity values
    articleId = getActivity().getIntent().getStringExtra(WidgetProvider.ITEM_ID);
    permalink = getActivity().getIntent().getStringExtra(WidgetProvider.ITEM_PERMALINK);

    ll = new LinearLayout(mContext);
    ll.setLayoutParams(new WebView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT, 0, 0));
    // fixes for webview not taking keyboard input on some devices
    mWebView = new WebView(mContext);
    mWebView.setLayoutParams(new WebView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT, 0, 0));
    ll.addView(mWebView);//from  w  ww  . j ava 2  s  .  c om
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true); // enable ecmascript
    webSettings.setDomStorageEnabled(true); // some video sites require dom storage
    webSettings.setSupportZoom(false);
    webSettings.setBuiltInZoomControls(false);
    webSettings.setDisplayZoomControls(false);
    int fontSize = Integer.parseInt(mSharedPreferences.getString("commentfontpref", "18"));
    webSettings.setDefaultFontSize(fontSize);
    webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

    mSharedPreferences.getString("titlefontpref", "16");

    final String themeStr = global.mThemeManager.getActiveTheme("appthemepref").getValuesString();
    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            boolean redditLink = false;
            System.out.println(url);
            if (url.indexOf("file://") == 0) { // fix for short sub and user links
                url = url.replace("file://", "https://www.reddit.com") + "/.compact";
                redditLink = true;
            }
            if (redditLink || url.indexOf("https://www.reddit.com/") == 0) {
                Intent i = new Intent(mContext, WebViewActivity.class);
                i.putExtra("url", url);
                startActivity(i);
            } else {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
            }
            return true; // always override url
        }

        public void onPageFinished(WebView view, String url) {
            mWebView.loadUrl("javascript:init(\"" + StringEscapeUtils.escapeJavaScript(themeStr) + "\", \""
                    + global.mRedditData.getUsername() + "\")");
            if (load)
                load();
        }
    });
    mWebView.setWebChromeClient(new WebChromeClient());

    mWebView.requestFocus(View.FOCUS_DOWN);
    WebInterface webInterface = new WebInterface(mContext);
    mWebView.addJavascriptInterface(webInterface, "Reddinator");

    mWebView.loadUrl("file:///android_asset/comments.html#" + articleId);
}

From source file:com.xamoom.android.xamoomcontentblocks.ViewHolders.ContentBlock2ViewHolder.java

public ContentBlock2ViewHolder(View itemView, Fragment fragment, String youtubeApiKey,
        LruCache<String, Bitmap> bitmapCache) {
    super(itemView);

    mYoutubeApiKey = youtubeApiKey;//from  w  w  w  . java 2  s .  c om
    mContext = fragment.getContext();
    mFragment = fragment;
    mBitmapCache = bitmapCache;
    mFileManager = FileManager.getInstance(fragment.getContext());

    mTitleTextView = (TextView) itemView.findViewById(R.id.titleTextView);
    mFramelayout = (FrameLayout) itemView.findViewById(R.id.youtube_frame_layout);
    mYouTubeThumbnailView = (YouTubeThumbnailView) itemView.findViewById(R.id.youtube_thumbnail_view);
    mVideoWebView = (WebView) itemView.findViewById(R.id.videoWebView);
    mVideoWebView.setWebViewClient(new WebViewClient());
    mWebViewOverlay = itemView.findViewById(R.id.webViewOverlay);
    mVideoPlayImageView = (ImageView) itemView.findViewById(R.id.video_play_image_view);
    mProgressBar = (ProgressBar) itemView.findViewById(R.id.video_progress_bar);
    mVideoView = (VideoView) itemView.findViewById(R.id.videoView);
    mIntent = null;

    itemView.setOnClickListener(this);

    WebSettings webSettings = mVideoWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
}

From source file:uk.ac.hutton.ics.buntata.fragment.EulaFragment.java

private void showEulaForType(EulaUtils.EulaType type) {
    this.type = type;

    webView.setVisibility(View.VISIBLE);

    int resource = -1;
    switch (type) {
    case COMMERCIAL:
        resource = R.raw.eula_commercial;
        break;/*from ww  w .j a v  a2 s  . co m*/
    case CONSUMER:
        resource = R.raw.eula_consumer;
        break;
    }

    String prompt = "";
    try {
        InputStream inputStream = getResources().openRawResource(resource);
        byte[] buffer = new byte[inputStream.available()];
        inputStream.read(buffer);
        prompt = new String(buffer);
        inputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    webView.loadDataWithBaseURL(null, prompt, "text/html", "utf-8", null);

    webView.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
            buttonBar.setVisibility(View.VISIBLE);
        }

        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return handleUri(url);
        }

        @TargetApi(Build.VERSION_CODES.N)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return handleUri(request.getUrl().toString());
        }

        private boolean handleUri(String url) {
            if (url.startsWith("http:") || url.startsWith("https:")) {
                return false;
            }

            try {
                // Otherwise allow the OS to handle things like tel, mailto, etc.
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                getActivity().startActivity(intent);
                return true;
            } catch (ActivityNotFoundException e) {
                return false;
            }
        }
    });
}

From source file:com.example.ruby.mygetgps.ui.activities.MainActivity.java

private void setupWebView() {
    WebView webview = (WebView) findViewById(R.id.webview);
    webview.setWebChromeClient(new WebChromeClient() {
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }/*w  w  w  .  j  av  a 2s.c o m*/
    });
    webview.setWebViewClient(new WebViewClient());
    webview.clearCache(true);
    webview.clearHistory();
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    webview.loadUrl("https://getgpsserverrails-0.herokuapp.com/summaries");
}

From source file:org.alfresco.mobile.android.ui.oauth.OAuthFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (container == null) {
        return null;
    }//from   w  w  w.j  a va 2s.  c o m

    EventBusManager.getInstance().register(this);

    if (getArguments() != null && getArguments().containsKey(LAYOUT_ID)) {
        layout_id = getArguments().getInt(LAYOUT_ID);
    }

    View v = inflater.inflate(layout_id, container, false);

    if (this.apiKey == null) {
        this.apiKey = getText(R.string.oauth_api_key).toString();
    }
    if (this.apiSecret == null) {
        this.apiSecret = getText(R.string.oauth_api_secret).toString();
    }
    if (this.callback == null) {
        this.callback = getText(R.string.oauth_callback).toString();
    }
    if (this.scope == null) {
        this.scope = getText(R.string.oauth_scope).toString();
    }

    webview = (WebView) v.findViewById(R.id.webview);
    webview.getSettings().setJavaScriptEnabled(true);
    if (AndroidVersion.isLollipopOrAbove()) {
        webview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    }

    final FragmentActivity activity = getActivity();
    webview.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            // Activities and WebViews measure progress with different
            // scales.The progress meter will automatically disappear when
            // we reach 100%
            activity.setProgress(progress * 100);
        }
    });

    // attach WebViewClient to intercept the callback url
    webview.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // check for our custom callback protocol
            if (!isLoaded) {
                onCodeUrl(url);
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (!isLoaded) {
                onCodeUrl(url);
            }
            if (onOAuthWebViewListener != null) {
                onOAuthWebViewListener.onPageStarted(webview, url, favicon);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (onOAuthWebViewListener != null) {
                onOAuthWebViewListener.onPageFinished(webview, url);
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            if (onOAuthWebViewListener != null) {
                onOAuthWebViewListener.onReceivedError(webview, errorCode, description, failingUrl);
            }
        }

    });

    OAuthHelper helper = new OAuthHelper(baseOAuthUrl);
    // Log.d("OAUTH URL", helper.getAuthorizationUrl(apiKey, callback,
    // scope));
    // send user to authorization page
    webview.loadUrl(helper.getAuthorizationUrl(apiKey, callback, scope));

    return v;
}