Example usage for android.webkit WebView stopLoading

List of usage examples for android.webkit WebView stopLoading

Introduction

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

Prototype

public void stopLoading() 

Source Link

Document

Stops the current load.

Usage

From source file:com.anjalimacwan.fragment.NoteViewFragment.java

@SuppressLint("SetJavaScriptEnabled")
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override// w w  w .j  av  a 2  s  . com
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // Set values
    setRetainInstance(true);
    setHasOptionsMenu(true);

    // Get filename of saved note
    filename = getArguments().getString("filename");

    // Change window title
    String title;

    try {
        title = listener.loadNoteTitle(filename);
    } catch (IOException e) {
        title = getResources().getString(R.string.view_note);
    }

    getActivity().setTitle(title);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription(title, null,
                ContextCompat.getColor(getActivity(), R.color.primary));
        getActivity().setTaskDescription(taskDescription);
    }

    // Show the Up button in the action bar.
    ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Animate elevation change
    if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-large")
            && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        LinearLayout noteViewEdit = (LinearLayout) getActivity().findViewById(R.id.noteViewEdit);
        LinearLayout noteList = (LinearLayout) getActivity().findViewById(R.id.noteList);

        noteList.animate().z(0f);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
            noteViewEdit.animate()
                    .z(getResources().getDimensionPixelSize(R.dimen.note_view_edit_elevation_land));
        else
            noteViewEdit.animate().z(getResources().getDimensionPixelSize(R.dimen.note_view_edit_elevation));
    }

    // Set up content view
    TextView noteContents = (TextView) getActivity().findViewById(R.id.textView);
    markdownView = (MarkdownView) getActivity().findViewById(R.id.markdownView);

    // Apply theme
    SharedPreferences pref = getActivity().getSharedPreferences(getActivity().getPackageName() + "_preferences",
            Context.MODE_PRIVATE);
    ScrollView scrollView = (ScrollView) getActivity().findViewById(R.id.scrollView);
    String theme = pref.getString("theme", "light-sans");
    int textSize = -1;
    int textColor = -1;

    String fontFamily = null;

    if (theme.contains("light")) {
        if (noteContents != null) {
            noteContents.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_color_primary));
            noteContents.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
        }

        if (markdownView != null) {
            markdownView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
            textColor = ContextCompat.getColor(getActivity(), R.color.text_color_primary);
        }

        scrollView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
    }

    if (theme.contains("dark")) {
        if (noteContents != null) {
            noteContents.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_color_primary_dark));
            noteContents
                    .setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
        }

        if (markdownView != null) {
            markdownView
                    .setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
            textColor = ContextCompat.getColor(getActivity(), R.color.text_color_primary_dark);
        }

        scrollView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
    }

    if (theme.contains("sans")) {
        if (noteContents != null)
            noteContents.setTypeface(Typeface.SANS_SERIF);

        if (markdownView != null)
            fontFamily = "sans-serif";
    }

    if (theme.contains("serif")) {
        if (noteContents != null)
            noteContents.setTypeface(Typeface.SERIF);

        if (markdownView != null)
            fontFamily = "serif";
    }

    if (theme.contains("monospace")) {
        if (noteContents != null)
            noteContents.setTypeface(Typeface.MONOSPACE);

        if (markdownView != null)
            fontFamily = "monospace";
    }

    switch (pref.getString("font_size", "normal")) {
    case "smallest":
        textSize = 12;
        break;
    case "small":
        textSize = 14;
        break;
    case "normal":
        textSize = 16;
        break;
    case "large":
        textSize = 18;
        break;
    case "largest":
        textSize = 20;
        break;
    }

    if (noteContents != null)
        noteContents.setTextSize(textSize);

    if (markdownView != null) {
        String topBottom = " " + Float.toString(getResources().getDimension(R.dimen.padding_top_bottom)
                / getResources().getDisplayMetrics().density) + "px";
        String leftRight = " " + Float.toString(getResources().getDimension(R.dimen.padding_left_right)
                / getResources().getDisplayMetrics().density) + "px";
        String fontSize = " " + Integer.toString(textSize) + "px";
        String fontColor = " #" + StringUtils.remove(Integer.toHexString(textColor), "ff");

        final String css = "body { " + "margin:" + topBottom + topBottom + leftRight + leftRight + "; "
                + "font-family:" + fontFamily + "; " + "font-size:" + fontSize + "; " + "color:" + fontColor
                + "; " + "}";

        final String js = "var styleNode = document.createElement('style');\n"
                + "styleNode.type = \"text/css\";\n" + "var styleText = document.createTextNode('" + css
                + "');\n" + "styleNode.appendChild(styleText);\n"
                + "document.getElementsByTagName('head')[0].appendChild(styleNode);\n";

        markdownView.getSettings().setJavaScriptEnabled(true);
        markdownView.getSettings().setLoadsImagesAutomatically(false);
        markdownView.setWebViewClient(new WebViewClient() {
            @TargetApi(Build.VERSION_CODES.N)
            @Override
            public void onLoadResource(WebView view, String url) {
                view.stopLoading();
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException | FileUriExposedException e) {
                        /* Gracefully fail */ }
                else
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                        /* Gracefully fail */ }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
                    view.evaluateJavascript(js, null);
                else
                    view.loadUrl("javascript:" + js);
            }
        });
    }

    // Load note contents
    try {
        contentsOnLoad = listener.loadNote(filename);
    } catch (IOException e) {
        showToast(R.string.error_loading_note);

        // Add NoteListFragment or WelcomeFragment
        Fragment fragment;
        if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-normal"))
            fragment = new NoteListFragment();
        else
            fragment = new WelcomeFragment();

        getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteListFragment")
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
    }

    // Set TextView contents
    if (noteContents != null)
        noteContents.setText(contentsOnLoad);

    if (markdownView != null)
        markdownView.loadMarkdown(contentsOnLoad);

    // Show a toast message if this is the user's first time viewing a note
    final SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    firstLoad = sharedPref.getInt("first-load", 0);
    if (firstLoad == 0) {
        // Show dialog with info
        DialogFragment firstLoad = new FirstViewDialogFragment();
        firstLoad.show(getFragmentManager(), "firstloadfragment");

        // Set first-load preference to 1; we don't need to show the dialog anymore
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt("first-load", 1);
        editor.apply();
    }

    // Detect single and double-taps using GestureDetector
    final GestureDetector detector = new GestureDetector(getActivity(),
            new GestureDetector.OnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return false;
                }

                @Override
                public void onShowPress(MotionEvent e) {
                }

                @Override
                public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                    return false;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                }

                @Override
                public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                    return false;
                }

                @Override
                public boolean onDown(MotionEvent e) {
                    return false;
                }
            });

    detector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            if (sharedPref.getBoolean("show_double_tap_message", true)) {
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putBoolean("show_double_tap_message", false);
                editor.apply();
            }

            Bundle bundle = new Bundle();
            bundle.putString("filename", filename);

            Fragment fragment = new NoteEditFragment();
            fragment.setArguments(bundle);

            getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteEditFragment")
                    .commit();

            return false;
        }

        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {
            return false;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            if (sharedPref.getBoolean("show_double_tap_message", true) && showMessage) {
                showToastLong(R.string.double_tap);
                showMessage = false;
            }

            return false;
        }

    });

    if (noteContents != null)
        noteContents.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                detector.onTouchEvent(event);
                return false;
            }
        });

    if (markdownView != null)
        markdownView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                detector.onTouchEvent(event);
                return false;
            }
        });
}

From source file:com.sonymobile.dronecontrol.activity.MainActivity.java

private void loadLicense() {
    View view = getLayoutInflater().inflate(R.layout.licenses, null);

    Dialog dialog = new AlertDialog.Builder(this).setPositiveButton(R.string.settings_button_ok, null)
            .setView(view).setTitle(getString(R.string.settings_item_licenses)).create();

    final WebView webView = (WebView) view.findViewById(R.id.license_view);
    final ProgressBar webProgress = (ProgressBar) view.findViewById(R.id.license_progress);
    webProgress.setVisibility(View.VISIBLE);

    dialog.setOnDismissListener(new OnDismissListener() {
        @Override/*from www. j  a  v  a  2 s .c  o  m*/
        public void onDismiss(DialogInterface dialog) {
            webView.stopLoading();
        }
    });

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

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

        @Override
        public void onScaleChanged(WebView view, float oldScale, float newScale) {
            super.onScaleChanged(view, oldScale, newScale);
            webProgress.setVisibility(View.GONE);
        }

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

    webView.loadUrl("file:///android_asset/licenses.html");
    dialog.show();
}

From source file:com.facebook.react.views.webview.ReactWebViewManager.java

@Override
public void receiveCommand(WebView root, int commandId, @Nullable ReadableArray args) {
    switch (commandId) {
    case COMMAND_GO_BACK:
        root.goBack();/*  w  w w. j a  v a 2s  .co m*/
        break;
    case COMMAND_GO_FORWARD:
        root.goForward();
        break;
    case COMMAND_RELOAD:
        root.reload();
        break;
    case COMMAND_STOP_LOADING:
        root.stopLoading();
        break;
    case COMMAND_POST_MESSAGE:
        try {
            JSONObject eventInitDict = new JSONObject();
            eventInitDict.put("data", args.getString(0));
            root.loadUrl("javascript:(function () {" + "var event;" + "var data = " + eventInitDict.toString()
                    + ";" + "try {" + "event = new MessageEvent('message', data);" + "} catch (e) {"
                    + "event = document.createEvent('MessageEvent');"
                    + "event.initMessageEvent('message', true, true, data.data, data.origin, data.lastEventId, data.source);"
                    + "}" + "document.dispatchEvent(event);" + "})();");
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        break;
    case COMMAND_INJECT_JAVASCRIPT:
        root.loadUrl("javascript:" + args.getString(0));
        break;
    }
}

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));

    }/* www  .jav  a2s.  com*/
    // 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:eu.vranckaert.worktime.utils.donations.DonationsFragment.java

/**
 * Build view for Flattr. see Flattr API for more information:
 * http://developers.flattr.net/button///from ww  w . j  a  v a 2  s .c  o m
 */
@SuppressLint("SetJavaScriptEnabled")
@TargetApi(11)
private void buildFlattrView() {
    final FrameLayout mLoadingFrame;
    final WebView mFlattrWebview;

    mFlattrWebview = (WebView) getActivity().findViewById(R.id.donations__flattr_webview);
    mLoadingFrame = (FrameLayout) getActivity().findViewById(R.id.donations__loading_frame);

    // disable hardware acceleration for this webview to get transparent background working
    if (Build.VERSION.SDK_INT >= 11) {
        mFlattrWebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    // define own webview client to override loading behaviour
    mFlattrWebview.setWebViewClient(new WebViewClient() {
        /**
         * Open all links in browser, not in webview
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
            view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlNewString)));

            return false;
        }

        /**
         * Links in the flattr iframe should load in the browser not in the iframe itself,
         * http:/
         * /stackoverflow.com/questions/5641626/how-to-get-webview-iframe-link-to-launch-the
         * -browser
         */
        @Override
        public void onLoadResource(WebView view, String url) {
            if (url.contains("flattr")) {
                HitTestResult result = view.getHitTestResult();
                if (result != null && result.getType() > 0) {
                    view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    view.stopLoading();
                }
            }
        }

        /**
         * After loading is done, remove frame with progress circle
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            // remove loading frame, show webview
            if (mLoadingFrame.getVisibility() == View.VISIBLE) {
                mLoadingFrame.setVisibility(View.GONE);
                mFlattrWebview.setVisibility(View.VISIBLE);
            }
        }
    });

    // get flattr values from xml config
    String projectUrl = DonationsUtils.getResourceString(getActivity(), "donations__flattr_project_url");
    String flattrUrl = DonationsUtils.getResourceString(getActivity(), "donations__flattr_url");

    // make text white and background transparent
    String htmlStart = "<html> <head><style type='text/css'>*{color: #FFFFFF; background-color: transparent;}</style>";

    // https is not working in android 2.1 and 2.2
    String flattrScheme;
    if (Build.VERSION.SDK_INT >= 9) {
        flattrScheme = "https://";
    } else {
        flattrScheme = "http://";
    }

    // set url of flattr link
    mFlattrUrl = (TextView) getActivity().findViewById(R.id.donations__flattr_url);
    mFlattrUrl.setText(flattrScheme + flattrUrl);

    String flattrJavascript = "<script type='text/javascript'>" + "/* <![CDATA[ */" + "(function() {"
            + "var s = document.createElement('script'), t = document.getElementsByTagName('script')[0];"
            + "s.type = 'text/javascript';" + "s.async = true;" + "s.src = '" + flattrScheme
            + "api.flattr.com/js/0.6/load.js?mode=auto';" + "t.parentNode.insertBefore(s, t);" + "})();"
            + "/* ]]> */" + "</script>";
    String htmlMiddle = "</head> <body> <div align='center'>";
    String flattrHtml = "<a class='FlattrButton' style='display:none;' href='" + projectUrl
            + "' target='_blank'></a> <noscript><a href='" + flattrScheme + flattrUrl
            + "' target='_blank'> <img src='" + flattrScheme
            + "api.flattr.com/button/flattr-badge-large.png' alt='Flattr this' title='Flattr this' border='0' /></a></noscript>";
    String htmlEnd = "</div> </body> </html>";

    String flattrCode = htmlStart + flattrJavascript + htmlMiddle + flattrHtml + htmlEnd;

    mFlattrWebview.getSettings().setJavaScriptEnabled(true);

    mFlattrWebview.loadData(flattrCode, "text/html", "utf-8");

    // make background of webview transparent
    // has to be called AFTER loadData
    // http://stackoverflow.com/questions/5003156/android-webview-style-background-colortransparent-ignored-on-android-2-2
    mFlattrWebview.setBackgroundColor(0x00000000);
}

From source file:com.zion.htf.ui.InfoDetailsActivity.java

@Override
public void onCreate(Bundle savedInstance) {
    super.onCreate(savedInstance);

    this.context = this;

    String resourceName = this.getIntent().getStringExtra(InfoDetailsActivity.name);
    if (null == resourceName) {
        throw new RuntimeException("This requires a 'name' parameter in its starting intent.");
    }//from   w ww .ja  v a2s.c o  m

    this.setTitle(this.getString(this.getResources().getIdentifier(resourceName, "string", "com.zion.htf")));

    this.webView = new WebView(this);
    this.webView.loadDataWithBaseURL("file:///android_res/raw/", this.readTextFromResource(resourceName),
            "text/html", "utf-8", null);
    this.webView.setBackgroundColor(0x00000000);
    if ("info_about".equals(resourceName) || "info_open_source".equals(resourceName))
        this.webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.v(InfoDetailsActivity.TAG, url);
                boolean ret = false;
                if (url.contains("github.com/nstCactus")) {
                    InfoDetailsActivity.this.startActivity(new Intent(Intent.ACTION_VIEW,
                            Uri.parse("https://github.com/nstCactus/Hadra-Trance-Festival")));
                    ret = true;
                } else if (url.contains("donate.me")) {
                    InfoDetailsActivity.this
                            .startActivity(new Intent(InfoDetailsActivity.this, DonateActivity.class));
                    ret = true;
                } else if (url.contains("mailto:")) {
                    Log.v(url, url);
                    InfoDetailsActivity.this.startActivity(new Intent(Intent.ACTION_SENDTO, Uri.parse(url)));
                    ret = true;
                }

                return ret;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                Log.v(InfoDetailsActivity.TAG, "onPageStarted called");
                if (shouldOverrideUrlLoading(view, url)) {
                    view.stopLoading();
                }
            }
        });

    this.setContentView(this.webView);

}

From source file:com.concentricsky.android.khanacademy.app.ShowProfileActivity.java

/**
 * Get the current user, and fail if there is none.
 *///  w ww .  j a v a2  s . c  o m
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    destroyed = false;
    this.webViewTimeoutPromptDialog = new AlertDialog.Builder(this)
            .setMessage("The page is taking a long time to respond. Stop loading?")
            .setPositiveButton("Stop", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    if (webView != null) {
                        webView.stopLoading();
                        finish();
                    }
                }
            }).setNegativeButton("Wait", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    stopWebViewLoadTimeout();
                }
            }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    startWebViewLoadTimeout();
                }
            }).create();

    getActionBar().setDisplayHomeAsUpEnabled(true);

    setContentView(R.layout.profile);
    setTitle(getString(R.string.profile_title));
    webView = (WebView) findViewById(R.id.web_view);
    webView.setMinimumWidth(800);
    enableJavascript(webView);
    webView.getSettings().setDefaultZoom(ZoomDensity.FAR);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {
            Log.d(LOG_TAG, "shouldOverrideUrlLoading: " + url);
            URL parsed = null;
            try {
                parsed = new URL(url);
            } catch (MalformedURLException e) {
                // Let the webview figure that one out.
                return false;
            }

            // Only ka links will load in this webview.
            if (parsed.getHost().equals("www.khanacademy.org")) {

                // Video urls should link into video detail. See below for another video url format.
                if (parsed.getPath().equals("/video")) {
                    String query = parsed.getQuery();
                    if (query != null && query.length() > 0) {
                        String[] items = query.split("&");
                        String videoId = null;
                        for (String item : items) {
                            String[] parts = item.split("=", 2);
                            if (parts.length > 1) {
                                if ("v".equals(parts[0])) {
                                    videoId = parts[1];
                                    break;
                                }
                            }
                        }
                        if (videoId != null) {
                            String[] ids = normalizeVideoAndTopicId(videoId, "");
                            if (ids != null) {
                                launchVideoDetailActivity(ids[0], ids[1]);
                                return true;
                            }
                        }
                    }
                    // There was no ?v= or something weird is going on. Allow the page
                    // load, which should hit KA's nice "no video found" page.
                    showSpinner();
                    startWebViewLoadTimeout();
                    return false;
                }

                if (parsed.getPath().startsWith("/profile")) {
                    // navigation within the profile makes sense here.
                    showSpinner();
                    startWebViewLoadTimeout();
                    return false;
                }

                // Embedded logout option (in upper left menu) can be intercepted and cause the app to be logged out as well.
                if (parsed.getPath().equals("/logout")) {
                    if (dataService != null) {
                        dataService.getAPIAdapter().logout();
                    }
                    finish();
                    return false; // try to let the webview hit logout to get the cookies cleared as we exit
                }

                // There is a new kind of video url now.. thanks guys..
                // http://www.khanacademy.org/video/subtraction-2
                //  redirects to
                // http://www.khanacademy.org/math/arithmetic/addition-subtraction/two_dig_add_sub/v/subtraction-2
                String[] path = parsed.getPath().split("/");
                List<String> parts = Arrays.asList(path);
                if (parts.contains("v")) {
                    String videoId = null;
                    String topicId = null;
                    for (int i = path.length - 1; i >= 0; --i) {
                        if (path[i].equals("v")) {
                            continue;
                        }
                        if (videoId == null) {
                            videoId = path[i];
                        } else if (topicId == null) {
                            topicId = path[i];
                        } else {
                            break;
                        }
                    }

                    if (videoId != null && topicId != null && dataService != null) {
                        // Looks like a video url. Double check that we have the topic and video before launching detail activity.
                        Log.d(LOG_TAG, "video and topic ids found; looks like a video url.");

                        String[] ids = normalizeVideoAndTopicId(videoId, topicId);
                        if (ids != null) {
                            launchVideoDetailActivity(ids[0], ids[1]);
                            return true;
                        }
                    }
                } else if (parsed.getPath().startsWith("/video")) {
                    String videoId = path[path.length - 1];
                    String[] ids = normalizeVideoAndTopicId(videoId, "");
                    if (ids != null) {
                        launchVideoDetailActivity(ids[0], ids[1]);
                        return true;
                    }
                }

                //               showSpinner();
                //               startWebViewLoadTimeout();
                //               return false;
            }

            // All other urls should launch in the browser instead of here, except hash changes if we can distinguish.
            loadInBrowser(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            Log.d(LOG_TAG, "onPageFinished");
            stopWebViewLoadTimeout();
            if (!destroyed) {
                hideSpinner();
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d(LOG_TAG, "onPageStarted");
            stopWebViewLoadTimeout();

            //            view.loadUrl("javascript:document.addEventListener( 'DOMContentLoaded',function() {AndroidApplication.jqueryReady()} );");

            //            handler.postDelayed(new Runnable() {
            //               @Override
            //               public void run() {
            //                  if (!destroyed) {
            //                     hijack();
            //                  }
            //               }
            //            }, 100);
        }
    });
    //      webView.addJavascriptInterface(new Object() {
    //         public void log(String msg) {
    //            Log.d(LOG_TAG, "JSLOG: " + msg);
    //         }
    //         public void jqueryReady() {
    //            Log.d(LOG_TAG, "javascript: jqueryReady");
    //            hijack();
    //         }
    //      }, "AndroidApplication");
    //      
    showSpinner();

    requestDataService(new ObjectCallback<KADataService>() {
        @Override
        public void call(KADataService service) {
            dataService = service;
            api = service.getAPIAdapter();

            String[] credentials = getCurrentLoginCredentials();
            loginUser(credentials[0], credentials[1]);
        }
    });
}

From source file:at.maui.cheapcast.fragment.DonationsFragment.java

/**
 * Build view for Flattr. see Flattr API for more information:
 * http://developers.flattr.net/button/// ww w . j ava  2 s .  c om
 */
@SuppressLint("SetJavaScriptEnabled")
@TargetApi(11)
private void buildFlattrView() {
    final FrameLayout mLoadingFrame;
    final WebView mFlattrWebview;

    mFlattrWebview = (WebView) getActivity().findViewById(R.id.donations__flattr_webview);
    mLoadingFrame = (FrameLayout) getActivity().findViewById(R.id.donations__loading_frame);

    // disable hardware acceleration for this webview to get transparent background working
    if (Build.VERSION.SDK_INT >= 11) {
        mFlattrWebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    // define own webview client to override loading behaviour
    mFlattrWebview.setWebViewClient(new WebViewClient() {
        /**
         * Open all links in browser, not in webview
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
            try {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlNewString)));
            } catch (ActivityNotFoundException e) {
                openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title,
                        getString(R.string.donations__alert_dialog_no_browser));
            }

            return false;
        }

        /**
         * Links in the flattr iframe should load in the browser not in the iframe itself,
         * http:/
         * /stackoverflow.com/questions/5641626/how-to-get-webview-iframe-link-to-launch-the
         * -browser
         */
        @Override
        public void onLoadResource(WebView view, String url) {
            if (url.contains("flattr")) {
                HitTestResult result = view.getHitTestResult();
                if (result != null && result.getType() > 0) {
                    try {
                        view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    } catch (ActivityNotFoundException e) {
                        openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title,
                                getString(R.string.donations__alert_dialog_no_browser));
                    }
                    view.stopLoading();
                }
            }
        }

        /**
         * After loading is done, remove frame with progress circle
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            // remove loading frame, show webview
            if (mLoadingFrame.getVisibility() == View.VISIBLE) {
                mLoadingFrame.setVisibility(View.GONE);
                mFlattrWebview.setVisibility(View.VISIBLE);
            }
        }
    });

    // get flattr values from xml config
    String projectUrl = mFlattrProjectUrl;
    String flattrUrl = this.mFlattrUrl;

    // make text white and background transparent
    String htmlStart = "<html> <head><style type='text/css'>*{color: #FFFFFF; background-color: transparent;}</style>";

    // https is not working in android 2.1 and 2.2
    String flattrScheme;
    if (Build.VERSION.SDK_INT >= 9) {
        flattrScheme = "https://";
    } else {
        flattrScheme = "http://";
    }

    // set url of flattr link
    mFlattrUrlTextView = (TextView) getActivity().findViewById(R.id.donations__flattr_url);
    mFlattrUrlTextView.setText(flattrScheme + flattrUrl);

    String flattrJavascript = "<script type='text/javascript'>" + "/* <![CDATA[ */" + "(function() {"
            + "var s = document.createElement('script'), t = document.getElementsByTagName('script')[0];"
            + "s.type = 'text/javascript';" + "s.async = true;" + "s.src = '" + flattrScheme
            + "api.flattr.com/js/0.6/load.js?mode=auto';" + "t.parentNode.insertBefore(s, t);" + "})();"
            + "/* ]]> */" + "</script>";
    String htmlMiddle = "</head> <body> <div align='center'>";
    String flattrHtml = "<a class='FlattrButton' style='display:none;' href='" + projectUrl
            + "' target='_blank'></a> <noscript><a href='" + flattrScheme + flattrUrl
            + "' target='_blank'> <img src='" + flattrScheme
            + "api.flattr.com/button/flattr-badge-large.png' alt='Flattr this' title='Flattr this' border='0' /></a></noscript>";
    String htmlEnd = "</div> </body> </html>";

    String flattrCode = htmlStart + flattrJavascript + htmlMiddle + flattrHtml + htmlEnd;

    mFlattrWebview.getSettings().setJavaScriptEnabled(true);

    mFlattrWebview.loadData(flattrCode, "text/html", "utf-8");

    // disable scroll on touch
    mFlattrWebview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            // already handled (returns true) when moving
            return (motionEvent.getAction() == MotionEvent.ACTION_MOVE);
        }
    });

    // make background of webview transparent
    // has to be called AFTER loadData
    // http://stackoverflow.com/questions/5003156/android-webview-style-background-colortransparent-ignored-on-android-2-2
    mFlattrWebview.setBackgroundColor(0x00000000);
}

From source file:jahirfiquitiva.iconshowcase.fragments.DonationsFragment.java

/**
 * Build view for Flattr. see Flattr API for more information:
 * http://developers.flattr.net/button//*from   ww  w  .j  av  a2 s  .c om*/
 */
@SuppressLint("SetJavaScriptEnabled")
@TargetApi(11)
private void buildFlattrView() {
    final FrameLayout mLoadingFrame;
    final WebView mFlattrWebview;

    mFlattrWebview = (WebView) getActivity().findViewById(R.id.donations__flattr_webview);
    mLoadingFrame = (FrameLayout) getActivity().findViewById(R.id.donations__loading_frame);

    // disable hardware acceleration for this webview to get transparent background working
    if (Build.VERSION.SDK_INT >= 11) {
        mFlattrWebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    // define own webview client to override loading behaviour
    mFlattrWebview.setWebViewClient(new WebViewClient() {
        /**
         * Open all links in browser, not in webview
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
            try {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlNewString)));
            } catch (ActivityNotFoundException e) {
                openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title,
                        getString(R.string.donations__alert_dialog_no_browser));
            }

            return false;
        }

        /**
         * Links in the flattr iframe should load in the browser not in the iframe itself,
         * http:/
         * /stackoverflow.com/questions/5641626/how-to-get-webview-iframe-link-to-launch-the
         * -browser
         */
        @Override
        public void onLoadResource(WebView view, String url) {
            if (url.contains("flattr")) {
                WebView.HitTestResult result = view.getHitTestResult();
                if (result != null && result.getType() > 0) {
                    try {
                        view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    } catch (ActivityNotFoundException e) {
                        openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title,
                                getString(R.string.donations__alert_dialog_no_browser));
                    }
                    view.stopLoading();
                }
            }
        }

        /**
         * After loading is done, remove frame with progress circle
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            // remove loading frame, show webview
            if (mLoadingFrame.getVisibility() == View.VISIBLE) {
                mLoadingFrame.setVisibility(View.GONE);
                mFlattrWebview.setVisibility(View.VISIBLE);
            }
        }
    });

    // make text white and background transparent
    String htmlStart = "<html> <head><style type='text/css'>*{color: #FFFFFF; background-color: transparent;}</style>";

    // https is not working in android 2.1 and 2.2
    String flattrScheme;
    if (Build.VERSION.SDK_INT >= 9) {
        flattrScheme = "https://";
    } else {
        flattrScheme = "http://";
    }

    // set url of flattr link
    TextView mFlattrUrlTextView = (TextView) getActivity().findViewById(R.id.donations__flattr_url);
    mFlattrUrlTextView.setText(flattrScheme + mFlattrUrl);

    String flattrJavascript = "<script type='text/javascript'>" + "/* <![CDATA[ */" + "(function() {"
            + "var s = document.createElement('script'), t = document.getElementsByTagName('script')[0];"
            + "s.type = 'text/javascript';" + "s.async = true;" + "s.src = '" + flattrScheme
            + "api.flattr.com/js/0.6/load.js?mode=auto';" + "t.parentNode.insertBefore(s, t);" + "})();"
            + "/* ]]> */" + "</script>";
    String htmlMiddle = "</head> <body> <div align='center'>";
    String flattrHtml = "<a class='FlattrButton' style='display:none;' href='" + mFlattrProjectUrl
            + "' target='_blank'></a> <noscript><a href='" + flattrScheme + mFlattrUrl
            + "' target='_blank'> <img src='" + flattrScheme
            + "api.flattr.com/button/flattr-badge-large.png' alt='Flattr this' title='Flattr this' border='0' /></a></noscript>";
    String htmlEnd = "</div> </body> </html>";

    String flattrCode = htmlStart + flattrJavascript + htmlMiddle + flattrHtml + htmlEnd;

    mFlattrWebview.getSettings().setJavaScriptEnabled(true);

    mFlattrWebview.loadData(flattrCode, "text/html", "utf-8");

    // disable scroll on touch
    mFlattrWebview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            // already handled (returns true) when moving
            return (motionEvent.getAction() == MotionEvent.ACTION_MOVE);
        }
    });

    // make background of webview transparent
    // has to be called AFTER loadData
    // http://stackoverflow.com/questions/5003156/android-webview-style-background-colortransparent-ignored-on-android-2-2
    mFlattrWebview.setBackgroundColor(0x00000000);
}

From source file:org.sufficientlysecure.donations.DonationsFragment.java

/**
 * Build view for Flattr. see Flattr API for more information:
 * http://developers.flattr.net/button/// ww w  .  j  a va 2  s. co m
 */
@SuppressLint("SetJavaScriptEnabled")
@TargetApi(11)
private void buildFlattrView() {
    final FrameLayout mLoadingFrame;
    final WebView mFlattrWebview;

    mFlattrWebview = (WebView) getActivity().findViewById(R.id.donations__flattr_webview);
    mLoadingFrame = (FrameLayout) getActivity().findViewById(R.id.donations__loading_frame);

    // disable hardware acceleration for this webview to get transparent background working
    if (Build.VERSION.SDK_INT >= 11) {
        mFlattrWebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    // define own webview client to override loading behaviour
    mFlattrWebview.setWebViewClient(new WebViewClient() {
        /**
         * Open all links in browser, not in webview
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
            try {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlNewString)));
            } catch (ActivityNotFoundException e) {
                openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title,
                        getString(R.string.donations__alert_dialog_no_browser));
            }

            return false;
        }

        /**
         * Links in the flattr iframe should load in the browser not in the iframe itself,
         * http:/
         * /stackoverflow.com/questions/5641626/how-to-get-webview-iframe-link-to-launch-the
         * -browser
         */
        @Override
        public void onLoadResource(WebView view, String url) {
            if (url.contains("flattr")) {
                HitTestResult result = view.getHitTestResult();
                if (result != null && result.getType() > 0) {
                    try {
                        view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    } catch (ActivityNotFoundException e) {
                        openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title,
                                getString(R.string.donations__alert_dialog_no_browser));
                    }
                    view.stopLoading();
                }
            }
        }

        /**
         * After loading is done, remove frame with progress circle
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            // remove loading frame, show webview
            if (mLoadingFrame.getVisibility() == View.VISIBLE) {
                mLoadingFrame.setVisibility(View.GONE);
                mFlattrWebview.setVisibility(View.VISIBLE);
            }
        }
    });

    // make text white and background transparent
    String htmlStart = "<html> <head><style type='text/css'>*{color: #FFFFFF; background-color: transparent;}</style>";

    // https is not working in android 2.1 and 2.2
    String flattrScheme;
    if (Build.VERSION.SDK_INT >= 9) {
        flattrScheme = "https://";
    } else {
        flattrScheme = "http://";
    }

    // set url of flattr link
    mFlattrUrlTextView = (TextView) getActivity().findViewById(R.id.donations__flattr_url);
    mFlattrUrlTextView.setText(flattrScheme + mFlattrUrl);

    String flattrJavascript = "<script type='text/javascript'>" + "/* <![CDATA[ */" + "(function() {"
            + "var s = document.createElement('script'), t = document.getElementsByTagName('script')[0];"
            + "s.type = 'text/javascript';" + "s.async = true;" + "s.src = '" + flattrScheme
            + "api.flattr.com/js/0.6/load.js?mode=auto';" + "t.parentNode.insertBefore(s, t);" + "})();"
            + "/* ]]> */" + "</script>";
    String htmlMiddle = "</head> <body> <div align='center'>";
    String flattrHtml = "<a class='FlattrButton' style='display:none;' href='" + mFlattrProjectUrl
            + "' target='_blank'></a> <noscript><a href='" + flattrScheme + mFlattrUrl
            + "' target='_blank'> <img src='" + flattrScheme
            + "api.flattr.com/button/flattr-badge-large.png' alt='Flattr this' title='Flattr this' border='0' /></a></noscript>";
    String htmlEnd = "</div> </body> </html>";

    String flattrCode = htmlStart + flattrJavascript + htmlMiddle + flattrHtml + htmlEnd;

    mFlattrWebview.getSettings().setJavaScriptEnabled(true);

    mFlattrWebview.loadData(flattrCode, "text/html", "utf-8");

    // disable scroll on touch
    mFlattrWebview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            // already handled (returns true) when moving
            return (motionEvent.getAction() == MotionEvent.ACTION_MOVE);
        }
    });

    // make background of webview transparent
    // has to be called AFTER loadData
    // http://stackoverflow.com/questions/5003156/android-webview-style-background-colortransparent-ignored-on-android-2-2
    mFlattrWebview.setBackgroundColor(0x00000000);
}