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:de.baumann.browser.helper.helper_webView.java

public static void webView_WebViewClient(final Activity from, final SwipeRefreshLayout swipeRefreshLayout,
        final WebView webView, final EditText editText) {

    webView.setWebViewClient(new WebViewClient() {

        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            swipeRefreshLayout.setRefreshing(false);
            editText.setText(webView.getTitle());
            if (webView.getTitle() != null && !webView.getTitle().equals("about:blank")) {
                try {
                    final Database_History db = new Database_History(from);
                    db.addBookmark(webView.getTitle(), webView.getUrl());
                    db.close();//from   w  w  w  .  j a  v a  2 s.co  m
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            final Uri uri = Uri.parse(url);
            return handleUri(uri);
        }

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

        private boolean handleUri(final Uri uri) {

            Log.i(TAG, "Uri =" + uri);
            final String url = uri.toString();
            // Based on some condition you need to determine if you are going to load the url
            // in your web view itself or in a browser.
            // You can use `host` or `scheme` or any part of the `uri` to decide.

            if (url.startsWith("http"))
                return false;//open web links as usual
            //try to find browse activity to handle uri
            Uri parsedUri = Uri.parse(url);
            PackageManager packageManager = from.getPackageManager();
            Intent browseIntent = new Intent(Intent.ACTION_VIEW).setData(parsedUri);
            if (browseIntent.resolveActivity(packageManager) != null) {
                from.startActivity(browseIntent);
                return true;
            }
            //if not activity found, try to parse intent://
            if (url.startsWith("intent:")) {
                try {
                    Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                    if (intent.resolveActivity(from.getPackageManager()) != null) {
                        from.startActivity(intent);
                        return true;
                    }
                    //try to find fallback url
                    String fallbackUrl = intent.getStringExtra("browser_fallback_url");
                    if (fallbackUrl != null) {
                        webView.loadUrl(fallbackUrl);
                        return true;
                    }
                    //invite to install
                    Intent marketIntent = new Intent(Intent.ACTION_VIEW)
                            .setData(Uri.parse("market://details?id=" + intent.getPackage()));
                    if (marketIntent.resolveActivity(packageManager) != null) {
                        from.startActivity(marketIntent);
                        return true;
                    }
                } catch (URISyntaxException e) {
                    //not an intent uri
                }
            }
            return true;//do nothing in other cases
        }

    });
}

From source file:it.angrydroids.epub3reader.EpubReaderMain.java

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

    setContentView(R.layout.activity_epub_reader_main);

    // ----- get activity elements
    view1 = (WebView) findViewById(R.id.firstViewport);
    view2 = (WebView) findViewById(R.id.secondViewport);
    layout = (LinearLayout) findViewById(R.id.mainLayout);

    iconCloseView1 = (Button) findViewById(R.id.topRightFirstView);
    iconCloseView2 = (Button) findViewById(R.id.topRightSecondView);

    layoutView1 = (RelativeLayout) findViewById(R.id.firstViewportLayout);
    layoutView2 = (RelativeLayout) findViewById(R.id.secondViewportLayout);
    // -----/*from   w  w w.  j  a  v  a 2  s  . c o m*/

    // ----- get activity screen size
    DisplayMetrics metrics = this.getResources().getDisplayMetrics();
    screenWidth = metrics.widthPixels;
    screenHeight = metrics.heightPixels;
    // -----

    navigator = new EpubNavigator(getBaseContext());

    // enable JavaScript for cool things to happen!
    view1.getSettings().setJavaScriptEnabled(true);
    view2.getSettings().setJavaScriptEnabled(true);

    // when the app starts, only one view is shown
    updateView1(ViewStateEnum.books);
    updateView2(ViewStateEnum.invisible);

    // ----- SWIPE PAGE
    view1.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (stateView1 == ViewStateEnum.books) {
                swipePage(v, event, BookEnum.first);
            }

            if (syncScrollActivated == true && stateView2 != ViewStateEnum.invisible) {
                // syncScroll(v, view2, event); work in progress
            }

            WebView view = (WebView) v;
            return view.onTouchEvent(event);
        }
    });

    view2.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (stateView2 == ViewStateEnum.books) {
                swipePage(v, event, BookEnum.second);
            }
            WebView view = (WebView) v;
            return view.onTouchEvent(event);
        }
    });
    // -----

    // ----- VIEW CLOSING
    iconCloseView1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ViewStateEnum newState = navigator.closeView1();
            ViewStateEnum oldState = stateView1;
            updateView1(newState);
            if (oldState == ViewStateEnum.books) {
                updateView2(ViewStateEnum.invisible);
            }
        }
    });

    iconCloseView2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            updateView2(navigator.closeView2());
        }
    });
    // -----

    // ----- NOTE & LINK
    view1.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            if (stateView1 == ViewStateEnum.books || stateView1 == ViewStateEnum.notes) {
                Message msg = new Message();
                msg.setTarget(new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        String url = msg.getData().getString(getString(R.string.url));
                        if (url != null)
                            if (stateView1 == ViewStateEnum.books || stateView1 == ViewStateEnum.notes) {
                                updateView2(ViewStateEnum.notes);
                                navigator.setView2(url);
                            } else {
                                navigator.setView1(url);
                            }
                    }
                });
                view1.requestFocusNodeHref(msg);
            }
            return false;
        }
    });

    view1.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            try {
                updateView1(navigator.setView1(url));
            } catch (Exception e) {
                errorMessage(getString(R.string.error_LoadPage));
            }
            return true;
        }
    });

    view2.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Message msg = new Message();
            msg.setTarget(new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    String url = msg.getData().getString(getString(R.string.url));
                    if (url != null) {
                        try {
                            if (stateView2 == ViewStateEnum.books || stateView2 == ViewStateEnum.notes) {
                                updateView1(ViewStateEnum.notes);
                                navigator.setView1(url);
                            } else {
                                navigator.setView2(url);
                            }
                        } catch (Exception e) {
                            errorMessage(getString(R.string.error_LoadPage));
                        }
                    }

                }
            });
            view2.requestFocusNodeHref(msg);
            return false;
        }
    });

    view2.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            try {
                updateView2(navigator.setView2(url));
            } catch (Exception e) {
                errorMessage(getString(R.string.error_LoadPage));
            }
            return true;
        }
    });
    // -----

    // ----- LOAD STATE
    SharedPreferences preferences = getPreferences(MODE_PRIVATE);
    if (preferences.getBoolean(getString(R.string.bookOpen), false)) {
        loadState(preferences);
    } else {
        bookSelector = BookEnum.first;
        Intent goToChooser = new Intent(this, FileChooser.class);
        startActivityForResult(goToChooser, 0);
    }
    // -----
}

From source file:tv.acfun.a63.ArticleActivity.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override/*from  w w w  .j  av a  2 s. c  o m*/
protected void initView(Bundle savedInstanceState) {
    ARTICLE_PATH = AcApp.getExternalCacheDir("article").getAbsolutePath();

    Uri data = getIntent().getData();
    if (Intent.ACTION_VIEW.equalsIgnoreCase(getIntent().getAction()) && data != null) {
        String scheme = data.getScheme();
        if (scheme.equals("ac")) {
            // ac://ac000000
            aid = Integer.parseInt(getIntent().getDataString().substring(7));
        } else if (scheme.equals("http")) {
            // http://www.acfun.tv/v/ac123456
            Matcher matcher;
            String path = data.getPath();
            if (path == null) {
                finish();
                return;
            }
            if ((matcher = sVreg.matcher(path)).find() || (matcher = sAreg.matcher(path)).find()) {
                aid = Integer.parseInt(matcher.group(1));
            }
        }
        if (aid != 0)
            title = "ac" + aid;
        isWebMode = getIntent().getBooleanExtra("webmode", false) && aid == 0;
    } else {
        aid = getIntent().getIntExtra("aid", 0);
        title = getIntent().getStringExtra("title");
    }
    if (!isWebMode) {
        if (aid == 0)
            throw new IllegalArgumentException(" id");
        getSupportActionBar().setTitle("ac" + aid);
        MobclickAgent.onEvent(this, "view_article");
        db = new DB(this);
        isFaved = db.isFav(aid);
    }
    mWeb.getSettings().setAppCachePath(ARTICLE_PATH);
    mWeb.addJavascriptInterface(new ACJSObject(), "AC");
    // Set a chrome client to handle the MediaResource on web page
    // like video,video loading progress, etc.
    mWeb.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            setTitle(title);
        }
    });
    mWeb.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Matcher matcher = sAreg.matcher(url);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            if (matcher.find() || (matcher = sLiteAreg.matcher(url)).find()
                    || (matcher = sVreg.matcher(url)).find() || (matcher = sLiteVreg.matcher(url)).find()) {
                String acId = matcher.group(1);
                try {
                    intent.setData(Uri.parse("ac://ac" + acId));
                    startActivity(intent);
                    return true;
                } catch (Exception e) {
                    // nothing
                }

            } else if (Pattern.matches(sAppReg, url)) {
                String appLink = getString(R.string.app_ac_video_link);
                try {
                    intent.setData(Uri.parse(appLink));
                    startActivity(intent);
                    return true;
                } catch (Exception e) {
                    view.loadUrl(appLink);
                    return true;
                }

            }
            if (!isWebMode) {
                start(ArticleActivity.this, url);
                return true;
            } else {
                Uri uri = Uri.parse(url);
                if (uri.getHost() != null && !uri.getHost().contains("acfun")) {
                    try {
                        intent.setData(uri);
                        startActivity(intent);
                        return true;
                    } catch (ActivityNotFoundException ignored) {
                    }
                }
            }
            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            setSupportProgressBarIndeterminateVisibility(true);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            setSupportProgressBarIndeterminateVisibility(false);
            if (isWebMode || imgUrls == null || imgUrls.isEmpty() || url.startsWith("file:///android_asset")
                    || AcApp.getViewMode() == Constants.MODE_NO_PIC) // ?
                return;
            //                    Log.d(TAG, "on finished:" + url);
            if ((url.equals(getBaseUrl()) || url.contains(NAME_ARTICLE_HTML)) && imgUrls.size() > 0
                    && !isDownloaded) {
                String[] arr = new String[imgUrls.size()];
                mDownloadTask = new DownloadImageTask();
                mDownloadTask.execute(imgUrls.toArray(arr));
            }

        }

    });
    mWeb.getSettings().setSupportZoom(true);
    mWeb.getSettings().setBuiltInZoomControls(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        mWeb.getSettings().setDisplayZoomControls(false);
    setTextZoom(AcApp.getConfig().getInt("text_size", 0));
}

From source file:edu.tjhsst.ion.gcmFrame.MainActivity.java

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

    this.setContentView(R.layout.activity_main);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(getResources().getColor(R.color.navbar_color));

    }/* ww w.  j  ava 2s.  c om*/
    // requestWindowFeature(Window.FEATURE_NO_TITLE);

    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
            if (sentToken) {
                Log.i(TAG, "Google token sent");

            } else {
                Toast.makeText(getApplicationContext(), getString(R.string.token_error_message),
                        Toast.LENGTH_LONG).show();
            }
        }

    };

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
        if (ni != null) {
            NetworkInfo.State state = ni.getState();
            if (state == null || state != NetworkInfo.State.CONNECTED) {
                // record the fact that there is no connection
                isConnected = false;
            }
        }
    }

    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());
    boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.ION_SETUP, false);

    webView = (WebView) findViewById(R.id.webview);

    webView.setInitialScale(1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);

    webView.getSettings().setUseWideViewPort(true);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setScrollbarFadingEnabled(false);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }
    StringBuilder uaString = new StringBuilder(webView.getSettings().getUserAgentString());
    uaString.append(" - IonAndroid: gcmFrame (");
    if (sentToken) {
        uaString.append("appRegistered:True");
    } else {
        uaString.append("appRegistered:False");
    }
    uaString.append(" osVersion:").append(System.getProperty("os.version"));
    uaString.append(" apiLevel:").append(android.os.Build.VERSION.SDK_INT);
    uaString.append(" Device:").append(android.os.Build.DEVICE);
    uaString.append(" Model:").append(android.os.Build.MODEL);
    uaString.append(" Product:").append(android.os.Build.PRODUCT);
    uaString.append(")");
    webView.getSettings().setUserAgentString(uaString.toString());

    webView.setNetworkAvailable(isConnected);

    webView.addJavascriptInterface(new WebAppInterface(this), "IonAndroidInterface");

    webView.loadUrl(MainActivity.ION_HOST);

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d(TAG, "Loading " + url);
            if (!isConnected) {
                String html = getHtml("offline.html");
                html = html.replaceAll("\\[url\\]", url);
                view.loadData(html, "text/html", "utf-8");
                return true;
            } else if (url.contains(ION_HOST)) {
                // keep in WebView
                webView.loadUrl(url);
                return true;
            } else {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);
                return true;
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            // if (errorCode == ERROR_TIMEOUT)
            view.stopLoading(); // may not be needed
            String html = getHtml("timeout.html");
            html = html.replaceAll("\\[url\\]", failingUrl);
            html = html.replaceAll("\\[desc\\]", description);
            view.loadData(html, "text/html", "utf-8");
        }
    });

}

From source file:edu.cscie71.imm.slacker.plugin.Slacker.java

private void closeAuthScreen() {
    final WebView childView = this.inAppWebView;
    // The JS protects against multiple calls, so this should happen only when
    // closeDialog() is called by other native code.
    if (childView == null) {
        return;//w w  w  . j a va 2 s .c  o  m
    }
    this.cordova.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            childView.setWebViewClient(new WebViewClient() {
                // NB: wait for about:blank before dismissing
                public void onPageFinished(WebView view, String url) {
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                }
            });
            // NB: From SDK 19: "If you call methods on WebView from any thread
            // other than your app's UI thread, it can cause unexpected results."
            // http://developer.android.com/guide/webapps/migrating.html#Threads
            childView.loadUrl("about:blank");
        }
    });
}

From source file:de.mkrtchyan.recoverytools.SettingsFragment.java

public static void showChangelog(Context AppContext) {
    AlertDialog.Builder dialog = new AlertDialog.Builder(AppContext);
    dialog.setTitle(R.string.changelog);
    WebView changes = new WebView(AppContext);
    changes.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    changes.setWebViewClient(new WebViewClient());
    changes.loadUrl(Constants.CHANGELOG_URL);
    changes.clearCache(true);//from  w w w.  ja  v  a 2 s.c om
    dialog.setView(changes);
    dialog.show();
}

From source file:org.quantumbadger.redreader.fragments.WebViewFragment.java

@SuppressLint("NewApi")
@Override/*from   w w  w .ja va2  s  .  com*/
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {

    mActivity = (AppCompatActivity) getActivity();

    CookieSyncManager.createInstance(mActivity);

    outer = (FrameLayout) inflater.inflate(R.layout.web_view_fragment, null);

    final RedditPost src_post = getArguments().getParcelable("post");
    final RedditPreparedPost post;

    if (src_post != null) {

        final RedditParsedPost parsedPost = new RedditParsedPost(src_post, false);

        post = new RedditPreparedPost(mActivity, CacheManager.getInstance(mActivity), 0, parsedPost, -1, false,
                false);

    } else {
        post = null;
    }

    webView = (WebViewFixed) outer.findViewById(R.id.web_view_fragment_webviewfixed);
    final FrameLayout loadingViewFrame = (FrameLayout) outer
            .findViewById(R.id.web_view_fragment_loadingview_frame);

    /*handle download links show an alert box to load this outside the internal browser*/
    webView.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(final String url, String userAgent, String contentDisposition,
                String mimetype, long contentLength) {
            {
                new AlertDialog.Builder(mActivity).setTitle(R.string.download_link_title)
                        .setMessage(R.string.download_link_message)
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                Intent i = new Intent(Intent.ACTION_VIEW);
                                i.setData(Uri.parse(url));
                                getContext().startActivity(i);
                                mActivity.onBackPressed(); //get back from internal browser
                            }
                        }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                mActivity.onBackPressed(); //get back from internal browser
                            }
                        }).setIcon(android.R.drawable.ic_dialog_alert).show();
            }
        }
    });
    /*handle download links end*/

    progressView = new ProgressBar(mActivity, null, android.R.attr.progressBarStyleHorizontal);
    loadingViewFrame.addView(progressView);
    loadingViewFrame.setPadding(General.dpToPixels(mActivity, 10), 0, General.dpToPixels(mActivity, 10), 0);

    final WebSettings settings = webView.getSettings();

    settings.setBuiltInZoomControls(true);
    settings.setJavaScriptEnabled(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(false);
    settings.setUseWideViewPort(true);
    settings.setLoadWithOverviewMode(true);
    settings.setDomStorageEnabled(true);

    if (AndroidApi.isHoneyCombOrLater()) {
        settings.setDisplayZoomControls(false);
    }

    // TODO handle long clicks

    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, final int newProgress) {

            super.onProgressChanged(view, newProgress);

            AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                @Override
                public void run() {
                    progressView.setProgress(newProgress);
                    progressView.setVisibility(newProgress == 100 ? View.GONE : View.VISIBLE);
                }
            });
        }
    });

    if (mUrl != null) {
        webView.loadUrl(mUrl);
    } else {
        webView.loadDataWithBaseURL("https://reddit.com/", html, "text/html; charset=UTF-8", null, null);
    }

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, final String url) {

            if (url == null)
                return false;

            if (url.startsWith("data:")) {
                // Prevent imgur bug where we're directed to some random data URI
                return true;
            }

            // Go back if loading same page to prevent redirect loops.
            if (goingBack && currentUrl != null && url.equals(currentUrl)) {

                General.quickToast(mActivity,
                        String.format(Locale.US, "Handling redirect loop (level %d)", -lastBackDepthAttempt),
                        Toast.LENGTH_SHORT);

                lastBackDepthAttempt--;

                if (webView.canGoBackOrForward(lastBackDepthAttempt)) {
                    webView.goBackOrForward(lastBackDepthAttempt);
                } else {
                    mActivity.finish();
                }
            } else {

                if (RedditURLParser.parse(Uri.parse(url)) != null) {
                    LinkHandler.onLinkClicked(mActivity, url, false);
                } else {
                    webView.loadUrl(url);
                    currentUrl = url;
                }
            }

            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

            if (mUrl != null && url != null) {

                final AppCompatActivity activity = mActivity;

                if (activity != null) {
                    activity.setTitle(url);
                }
            }
        }

        @Override
        public void onPageFinished(final WebView view, final String url) {
            super.onPageFinished(view, url);

            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {

                    AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                        @Override
                        public void run() {

                            if (currentUrl == null || url == null)
                                return;

                            if (!url.equals(view.getUrl()))
                                return;

                            if (goingBack && url.equals(currentUrl)) {

                                General.quickToast(mActivity, String.format(Locale.US,
                                        "Handling redirect loop (level %d)", -lastBackDepthAttempt));

                                lastBackDepthAttempt--;

                                if (webView.canGoBackOrForward(lastBackDepthAttempt)) {
                                    webView.goBackOrForward(lastBackDepthAttempt);
                                } else {
                                    mActivity.finish();
                                }

                            } else {
                                goingBack = false;
                            }
                        }
                    });
                }
            }, 1000);
        }

        @Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
            super.doUpdateVisitedHistory(view, url, isReload);
        }
    });

    final FrameLayout outerFrame = new FrameLayout(mActivity);
    outerFrame.addView(outer);

    if (post != null) {

        final SideToolbarOverlay toolbarOverlay = new SideToolbarOverlay(mActivity);

        final BezelSwipeOverlay bezelOverlay = new BezelSwipeOverlay(mActivity,
                new BezelSwipeOverlay.BezelSwipeListener() {
                    @Override
                    public boolean onSwipe(@BezelSwipeOverlay.SwipeEdge int edge) {

                        toolbarOverlay.setContents(post.generateToolbar(mActivity, false, toolbarOverlay));
                        toolbarOverlay.show(
                                edge == BezelSwipeOverlay.LEFT ? SideToolbarOverlay.SideToolbarPosition.LEFT
                                        : SideToolbarOverlay.SideToolbarPosition.RIGHT);
                        return true;
                    }

                    @Override
                    public boolean onTap() {

                        if (toolbarOverlay.isShown()) {
                            toolbarOverlay.hide();
                            return true;
                        }

                        return false;
                    }
                });

        outerFrame.addView(bezelOverlay);
        outerFrame.addView(toolbarOverlay);

        bezelOverlay.getLayoutParams().width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;
        bezelOverlay.getLayoutParams().height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;

        toolbarOverlay.getLayoutParams().width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;
        toolbarOverlay.getLayoutParams().height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;
    }

    return outerFrame;
}

From source file:edu.cmu.sv.trailscribe.view.MapsActivity.java

@SuppressLint("SetJavaScriptEnabled")
private void setMap() {
    mWebView = (WebView) findViewById(R.id.maps_webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.addJavascriptInterface(this, "android");
    mWebView.setWebChromeClient(new WebChromeClient());
    mWebView.getSettings().setUseWideViewPort(false);
    mWebView.setWebViewClient(new WebViewClient());

    //      Setting to give OpenLayers access to local KML files
    //      Sets whether JavaScript running in the context of a file scheme URL should be allowed to 
    //      access content from any origin.
    mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);

    mController = new MapsController();
    mWebView.loadUrl(mController.getURL());
}

From source file:ca.rmen.android.networkmonitor.app.log.LogActivity.java

/**
 * Read the data from the DB, export it to an HTML file, and load the HTML file in the WebView.
 *//* w  w w  .j  av a 2  s  . c  om*/
private void loadHTMLFile() {
    Log.v(TAG, "loadHTMLFile");
    final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
    progressBar.setVisibility(View.VISIBLE);
    startRefreshIconAnimation();
    AsyncTask<Void, Void, File> asyncTask = new AsyncTask<Void, Void, File>() {

        @Override
        protected File doInBackground(Void... params) {
            Log.v(TAG, "loadHTMLFile:doInBackground");
            // Export the DB to the HTML file.
            HTMLExport htmlExport = new HTMLExport(LogActivity.this, false);
            int recordCount = NetMonPreferences.getInstance(LogActivity.this).getFilterRecordCount();
            return htmlExport.export(recordCount, null);
        }

        @SuppressLint("SetJavaScriptEnabled")
        @Override
        protected void onPostExecute(File result) {
            Log.v(TAG, "loadHTMLFile:onPostExecute, result=" + result);
            if (isFinishing()) {
                Log.v(TAG, "finishing, ignoring loadHTMLFile result");
                return;
            }
            if (result == null) {
                Toast.makeText(LogActivity.this, R.string.error_reading_log, Toast.LENGTH_LONG).show();
                return;
            }
            // Load the exported HTML file into the WebView.
            mWebView = (WebView) findViewById(R.id.web_view);
            // Save our current horizontal scroll position so we can keep our
            // horizontal position after reloading the page.
            final int oldScrollX = mWebView.getScrollX();
            mWebView.getSettings().setUseWideViewPort(true);
            mWebView.getSettings().setBuiltInZoomControls(true);
            mWebView.getSettings().setJavaScriptEnabled(true);
            mWebView.loadUrl("file://" + result.getAbsolutePath());
            mWebView.setWebViewClient(new WebViewClient() {

                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);
                    Log.v(TAG, "onPageStarted");
                    // Javascript hack to scroll back to our old X position.
                    // http://stackoverflow.com/questions/6855715/maintain-webview-content-scroll-position-on-orientation-change
                    if (oldScrollX > 0) {
                        String jsScrollX = "javascript:window:scrollTo(" + oldScrollX
                                + " / window.devicePixelRatio,0);";
                        view.loadUrl(jsScrollX);
                    }
                }

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

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    Log.v(TAG, "url: " + url);
                    // If the user clicked on one of the column names, let's update
                    // the sorting preference (column name, ascending or descending order).
                    if (url.startsWith(HTMLExport.URL_SORT)) {
                        NetMonPreferences prefs = NetMonPreferences.getInstance(LogActivity.this);
                        SortPreferences oldSortPreferences = prefs.getSortPreferences();
                        // The new column used for sorting will be the one the user tapped on.
                        String newSortColumnName = url.substring(HTMLExport.URL_SORT.length());
                        SortOrder newSortOrder = oldSortPreferences.sortOrder;
                        // If the user clicked on the column which is already used for sorting,
                        // toggle the sort order between ascending and descending.
                        if (newSortColumnName.equals(oldSortPreferences.sortColumnName)) {
                            if (oldSortPreferences.sortOrder == SortOrder.DESC)
                                newSortOrder = SortOrder.ASC;
                            else
                                newSortOrder = SortOrder.DESC;
                        }
                        // Update the sorting preferences (our shared preference change listener will be notified
                        // and reload the page).
                        prefs.setSortPreferences(new SortPreferences(newSortColumnName, newSortOrder));
                        return true;
                    }
                    // If the user clicked on the filter icon, start the filter activity for this column.
                    else if (url.startsWith(HTMLExport.URL_FILTER)) {
                        Intent intent = new Intent(LogActivity.this, FilterColumnActivity.class);
                        String columnName = url.substring(HTMLExport.URL_FILTER.length());
                        intent.putExtra(FilterColumnActivity.EXTRA_COLUMN_NAME, columnName);
                        startActivityForResult(intent, REQUEST_CODE_FILTER_COLUMN);
                        return true;
                    } else {
                        return super.shouldOverrideUrlLoading(view, url);
                    }
                }
            });
        }
    };
    asyncTask.execute();
}

From source file:org.safegees.safegees.gui.view.MainActivity.java

private void start() {
    if (DATA_STORAGE.getString(getResources().getString(R.string.KEY_USER_MAIL)) != null
            && DATA_STORAGE.getString(getResources().getString(R.string.KEY_USER_MAIL)).length() > 0) {
        shareDataWithServer();//from  www .j  a v  a 2 s  . co  m
    } else {

        /* TEST
        if(DATA_STORAGE.getString(getResources().getString(R.string.KEY_USER_MAIL)) != null && DATA_STORAGE.getString(getResources().getString(R.string.KEY_USER_MAIL)).length()>0){
        launchMainActivity();
        }else{
        //Start the loggin for result
        Intent loginInt = new Intent(this, LoginActivity.class);
        startActivityForResult(loginInt, 1);
        }*/

        if (Connectivity.isNetworkAvaiable(this) || StoredDataQuequesManager.getAppUsersMap(this).size() != 0) {

            final MainActivity mainActivity = this;

            //Download data
            this.adviceUser.setText(getResources().getString(R.string.splash_advice_download_info_hub));

            //Test
            //Not here at final
            final WebView webView = (WebView) this.findViewById(R.id.webview_info_pre_cache);
            final ArrayList<String> infoWebUrls = WebViewInfoWebDownloadController.getInfoUrlsArrayList();
            webView.setWebViewClient(new WebViewClient() {

                @Override
                public void onPageFinished(WebView view, String url) {
                    if (infoWebUrls.size() > 0) {
                        String nextUrl = infoWebUrls.get(0);
                        infoWebUrls.remove(nextUrl);
                        webView.loadUrl(nextUrl);
                    } else {
                        //Only one time
                        DATA_STORAGE.putBoolean(mainActivity.getResources().getString(R.string.KEY_INFO_WEB),
                                true);
                        //Start the loggin for result
                        Intent loginInt = new Intent(mainActivity, LoginActivity.class);
                        startActivityForResult(loginInt, 1);
                    }
                }
            });

            String nextUrl = infoWebUrls.get(0);
            infoWebUrls.remove(nextUrl);
            webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.setWebChromeClient(new WebChromeClient());

            if (StoredDataQuequesManager.getAppUsersMap(mainActivity).size() == 0
                    && !DATA_STORAGE.getBoolean(getResources().getString(R.string.KEY_INFO_WEB))) {
                webView.loadUrl(nextUrl);
            } else {
                if (DATA_STORAGE.getString(getResources().getString(R.string.KEY_USER_MAIL)) != null
                        && DATA_STORAGE.getString(getResources().getString(R.string.KEY_USER_MAIL))
                                .length() > 0) {
                    launchMainActivity();
                } else {
                    //Start the loggin for result
                    Intent loginInt = new Intent(mainActivity, LoginActivity.class);
                    startActivityForResult(loginInt, 1);
                }
            }

        } else {
            setNoInternetAdvice(this);
        }
    }
}