Example usage for android.webkit WebChromeClient WebChromeClient

List of usage examples for android.webkit WebChromeClient WebChromeClient

Introduction

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

Prototype

WebChromeClient

Source Link

Usage

From source file:com.safecell.LoginActivity.java

void dialogforWebview() {

    AlertDialog.Builder builder;//from  w  w w  .  j a v a  2s  .  c o  m

    Context mContext = LoginActivity.this;

    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
    View layout = inflater.inflate(R.layout.private_policy_layout, (ViewGroup) findViewById(R.id.layout_root));

    final Activity activity = LoginActivity.this;
    wv = (WebView) layout.findViewById(R.id.webview);

    wv.getSettings().setJavaScriptEnabled(true);
    wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

    wv.setWebViewClient(new HelloWebViewClient());
    wv.setWebChromeClient(new WebChromeClient() {

        public void onProgressChanged(WebView view, int newProgress) {
            activity.setProgress(newProgress * 100);

            if (newProgress == 100) {

            }
        };
    });

    wv.setWebViewClient(new WebViewClient() {
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            // Log.v("errorCode", "errorcode "+errorCode + description);
            alertDialogForTermsConditions.cancel();

        }
    });
    // wv.loadUrl(URLs.REMOTE_URL +
    // "api/1/site_setting/terms_of_service.html");
    wv.loadUrl("file:///android_asset/terms_of_service.html");
    builder = new AlertDialog.Builder(mContext);
    builder.setView(layout);
    builder.setTitle("Policy");

    builder.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            isTermsAcepted = true;
            dialog.cancel();
        }
    }).setNegativeButton("Don't Accept", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            isTermsAcepted = false;
            dialog.cancel();
            quitDialog("License", "Terms and conditions should accept. ");
        }
    });
    alertDialogForTermsConditions = builder.create();
    if (progressDialog != null && progressDialog.isShowing()) {
        progressDialog.dismiss();
    }
    try {
        alertDialogForTermsConditions.show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

private void openAuthScreen() {
    Runnable runnable = new Runnable() {
        @SuppressLint("NewApi")
        public void run() {
            dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);//from  ww  w.  j  a  va  2s.co m

            LinearLayout mainLayout = new LinearLayout(cordova.getActivity());
            mainLayout.setOrientation(LinearLayout.VERTICAL);

            inAppWebView = new WebView(cordova.getActivity());
            inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new WebChromeClient());
            WebViewClient client = new AuthBrowser();
            inAppWebView.setWebViewClient(client);
            WebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);

            inAppWebView.loadUrl(authURL + "?client_id=" + slackClientID + "&scope=" + scope);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.requestFocusFromTouch();

            mainLayout.addView(inAppWebView);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.MATCH_PARENT;

            dialog.setContentView(mainLayout);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
}

From source file:com.vikingbrain.dmt.view.RemoteControlActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_remote_control);

    davidBoxService = DMTApplication.getDavidBoxService();

    isKeyboardShowing = false;/* www  .  j a  va2 s . c o  m*/

    if (isTablet()) { //it's tablet
        mWebView = (WebView) findViewById(R.id.webviewXLarge);
    } else { //it's phone                  
        mWebViewTab1 = (WebView) findViewById(R.id.webviewtab1);
        mWebViewTab2 = (WebView) findViewById(R.id.webviewtab2);
        mWebViewTab3 = (WebView) findViewById(R.id.webviewtab3);
    }

    //Common configuration for web views
    WebChromeClient webChromeClient = new WebChromeClient();
    CustomWebViewClient customWebViewClient = new CustomWebViewClient();

    //phone vs tablet, the have different html pages
    if (isTablet()) { //it's tablet
        configureWebView(mWebView, webChromeClient, customWebViewClient);

        mWebView.loadUrl(Constants.PATH_ASSET_HTML_REMOTE_CONTROL_INDEX_TABLET);

    } else { //it's phone        

        configureWebView(mWebViewTab1, webChromeClient, customWebViewClient);
        configureWebView(mWebViewTab2, webChromeClient, customWebViewClient);
        configureWebView(mWebViewTab3, webChromeClient, customWebViewClient);

        //Quicknav is the default shown so it is priority
        mWebViewTab2.loadUrl(Constants.PATH_ASSET_HTML_REMOTE_CONTROL_QUICKNAV);
        mWebViewTab1.loadUrl(Constants.PATH_ASSET_HTML_REMOTE_CONTROL_NUMERIC);
        mWebViewTab3.loadUrl(Constants.PATH_ASSET_HTML_REMOTE_CONTROL_ADVANCED);

        //Tabs
        getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        ActionBar.Tab tab = getSupportActionBar().newTab();
        tab.setText(R.string.tab_numeric);
        tab.setTabListener(this);
        getSupportActionBar().addTab(tab, POSITION_TAB_NUMERIC);

        ActionBar.Tab tab2 = getSupportActionBar().newTab();
        tab2.setText(R.string.tab_quicknav);
        tab2.setTabListener(this);
        getSupportActionBar().addTab(tab2, POSITION_TAB_QUICKNAV);

        ActionBar.Tab tab3 = getSupportActionBar().newTab();
        tab3.setText(R.string.tab_advanced);
        tab3.setTabListener(this);
        getSupportActionBar().addTab(tab3, POSITION_TAB_ADVANCED);

        //Tab selected by default is number 2 (tab 1 is numbber 0)
        getSupportActionBar().setSelectedNavigationItem(POSITION_TAB_QUICKNAV);
    }

}

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

public MadvertiseMraidView(Context context) {
    super(context);
    setVerticalScrollBarEnabled(false);// w ww .j  a v  a2  s  .c  om
    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:com.citrus.sdk.CitrusActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    mPaymentType = getIntent().getParcelableExtra(Constants.INTENT_EXTRA_PAYMENT_TYPE);

    if (!(mPaymentType instanceof PaymentType.CitrusCash)) {
        setTheme(R.style.Base_Theme_AppCompat_Light_DarkActionBar);
    }//from w  w w.ja  va2 s .c o m

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_citrus);

    mPaymentParams = getIntent().getParcelableExtra(Constants.INTENT_EXTRA_PAYMENT_PARAMS);
    mCitrusConfig = CitrusConfig.getInstance();
    mActivityTitle = mCitrusConfig.getCitrusActivityTitle();

    mCitrusClient = CitrusClient.getInstance(mContext);

    // Set payment Params
    if (mPaymentParams != null) {
        mPaymentType = mPaymentParams.getPaymentType();
        mPaymentOption = mPaymentParams.getPaymentOption();
        mCitrusUser = mPaymentParams.getUser();

        mColorPrimary = mPaymentParams.getColorPrimary();
        mColorPrimaryDark = mPaymentParams.getColorPrimaryDark();
        mTextColorPrimary = mPaymentParams.getTextColorPrimary();
    } else if (mPaymentType != null) {
        mPaymentOption = mPaymentType.getPaymentOption();
        mCitrusUser = mPaymentType.getCitrusUser();

        mColorPrimary = mCitrusConfig.getColorPrimary();
        mColorPrimaryDark = mCitrusConfig.getColorPrimaryDark();
        mTextColorPrimary = mCitrusConfig.getTextColorPrimary();
    } else {
        throw new IllegalArgumentException("Payment Type Should not be null");
    }

    mActionBar = getSupportActionBar();
    mProgressDialog = new ProgressDialog(mContext);
    mPaymentWebview = (WebView) findViewById(R.id.payment_webview);
    mPaymentWebview.getSettings().setJavaScriptEnabled(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        /*
        This setting is required to enable redirection of urls from https to http or vice-versa.
        This redirection is blocked by default from Lollipop (Android 21).
         */
        mPaymentWebview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    }
    mPaymentWebview.addJavascriptInterface(new JsInterface(), Constants.JS_INTERFACE_NAME);

    mPaymentWebview.setWebChromeClient(new WebChromeClient());

    mPaymentWebview.setWebViewClient(new CitrusWebClient());

    // Make the webview visible only in case of PGPayment or LoadMoney.
    if (mPaymentType instanceof PaymentType.CitrusCash) {
        mPaymentWebview.setVisibility(View.GONE);
    }

    if (mPaymentType instanceof PaymentType.PGPayment || mPaymentType instanceof PaymentType.CitrusCash) {
        if (mPaymentType.getPaymentBill() != null) {
            // TODO Need to refactor the code.
            if (PaymentBill.toJSONObject(mPaymentType.getPaymentBill()) != null) {
                proceedToPayment(PaymentBill.toJSONObject(mPaymentType.getPaymentBill()).toString());
            }
        } else {
            fetchBill();
        }
    } else { //load cash does not requires Bill Generator
        Amount amount = mPaymentType.getAmount();

        LoadMoney loadMoney = new LoadMoney(amount.getValue(), mPaymentType.getUrl());
        PG paymentgateway = new PG(mPaymentOption, loadMoney,
                new UserDetails(CitrusUser.toJSONObject(mCitrusUser)));

        paymentgateway.load(CitrusActivity.this, new Callback() {
            @Override
            public void onTaskexecuted(String success, String error) {
                processresponse(success, error);
            }
        });
    }

    if (TextUtils.isEmpty(mActivityTitle)) {
        mActivityTitle = "Processing...";
    }

    setTitle(Html.fromHtml("<font color=\"" + mTextColorPrimary + "\">" + mActivityTitle + "</font>"));
    setActionBarBackground();
}

From source file:com.tarun.smartwomen.WebViewDemoActivity.java

@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
@Override//from w  w w  .j  a v a 2  s . c o  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.mainn);

    Intent intent = getIntent();
    reg = intent.getBooleanExtra("reg", false);

    i = (ImageView) findViewById(R.id.hj);

    try {

        big = new GifAnimationDrawable(getResources().openRawResource(R.raw.anim2));
        // big.setOneShot(true);
        android.util.Log.v("GifAnimationDrawable", "===>Four");
    } catch (IOException ioe) {

    }

    i.setImageDrawable(big);
    big.setVisible(true, true);

    sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
    // historyStack = new LinkedList<Link>();
    webview = (WebView) findViewById(R.id.webkit);

    WebSettings webSettings = webview.getSettings();
    webSettings.setJavaScriptEnabled(true);

    webSettings.setDomStorageEnabled(true);
    // webview.addJavascriptInterface(new WebViewDemoActivity(), "Android");
    // webview.getSettings().setJavaScriptEnabled(true);

    webview.getSettings().setBuiltInZoomControls(true);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
        // webview.getSettings().setPluginState(PluginState.ON);
        // webview.getSettings().setJavaScriptEnabled(true);
    } else {
        // IMPORTANT!! this method is no longer available since Android 4.3
        // so the code doesn't compile anymore
        // webview.getSettings().setPluginsEnabled(true);
    }

    // Internet

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    connected = false;
    if ((null != connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) && connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
            || (null != connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) && connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED)) {
        // we are connected to a network
        connected = true;
    }

    if (connected == false) {
        /*
         * Toast.makeText(Rss.this,
         * "Connect to internet and Restart Application",
         * Toast.LENGTH_SHORT).show();
         */
        webview.setVisibility(View.INVISIBLE);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(WebViewDemoActivity.this);

        // alertDialogBuilder.setTitle("Please connect to Internet");
        alertDialogBuilder.setMessage(
                "In order to provide the freshest recipes and juicing information this app must be connected to the internet, please check your internet settings");
        // set positive button: Yes message

        alertDialogBuilder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // cancel the alert box and put a Toast to the user

                startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
            }
        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        // show alert
        alertDialog.show();

    }

    // downloads
    // webview.setDownloadListener(new CustomDownloadListener());

    webview.setWebViewClient(new CustomWebViewClient());

    webview.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int progress) {

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {

        }

    });

    // http://stackoverflow.com/questions/2083909/android-webview-refusing-user-input
    webview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!v.hasFocus()) {
                    v.requestFocus();
                }
                break;
            }
            return false;
        }

    });

    if (reg == true) {
        if (Locale.getDefault().getLanguage().equals("es")) {

            webview.loadUrl("http://om-msmartwoman.com/member/register");
            // webview.loadUrl("http://live-juice-guru.gotpantheon.com/user/login");
        } else {
            webview.loadUrl("http://om-msmartwoman.com/member/register");
        }

        webview.requestFocus();
    } else {
        uhdj = sp.getString("your_int_key", "0");

        Log.e("Url is here ..............................", uhdj);
        // Welcome page loaded from assets directory
        if (Locale.getDefault().getLanguage().equals("es")) {

            webview.loadUrl(uhdj);
            // webview.loadUrl("http://live-juice-guru.gotpantheon.com/user/login");
        } else {
            webview.loadUrl(uhdj);
        }

        webview.requestFocus();
    }

}

From source file:org.artifactly.client.Artifactly.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/* w  ww . j a  va  2 s.  co m*/

    // Setting up the WebView
    webView = (WebView) findViewById(R.id.webview);
    webView.getSettings().setJavaScriptEnabled(true);

    webView.addJavascriptInterface(new JavaScriptInterface(), JAVASCRIPT_BRIDGE_PREFIX);

    // Disable the vertical scroll bar
    webView.setVerticalScrollBarEnabled(false);

    webView.setWebChromeClient(new WebChromeClient() {

        public boolean onConsoleMessage(ConsoleMessage cm) {

            Log.d(PROD_LOG_TAG, cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId());
            return true;
        }
    });

    webView.loadUrl(ARTIFACTLY_URL);

    /*
     * Calling startService so that the service keeps running. e.g. After application installation
     * The start of the service at boot is handled via a BroadcastReceiver and the BOOT_COMPLETED action
     */
    startService(new Intent(this, ArtifactlyService.class));

    // Bind to the service
    bindService(new Intent(this, ArtifactlyService.class), serviceConnection, BIND_AUTO_CREATE);
    isBound = true;

    // Instantiate the broadcast receiver
    locationUpdateBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            new GetArtifactsForCurrentLocationTask().execute();
        }
    };

    connectivityBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent arg1) {

            canAccessInternet = hasConnectivity();
        }
    };

    hasArtifactsAtCurrentLocationReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            if (null != localService) {

                Location location = localService.getLocation();
                callJavaScriptFunction(BROADCAST_CURRENT_LOCATION, locationToJSON(location));
            }
        }
    };

    // Initialize connectivity flag
    canAccessInternet = hasConnectivity();

    // Get version information from AndroidManifest.xml
    try {

        version = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
    } catch (NameNotFoundException e) {

        Log.w(PROD_LOG_TAG, "Exception accessing version information", e);
    }
}

From source file:com.alex.smartwomanmiddleeastfem.WebViewDemoActivity.java

@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
@Override//from   w  w w  .java2 s.co m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.mainn);

    Intent intent = getIntent();
    reg = intent.getBooleanExtra("reg", false);

    i = (ImageView) findViewById(R.id.hj);

    try {

        big = new GifAnimationDrawable(getResources().openRawResource(R.raw.anim2));
        // big.setOneShot(true);
        android.util.Log.v("GifAnimationDrawable", "===>Four");
    } catch (IOException ioe) {

    }

    i.setImageDrawable(big);
    big.setVisible(true, true);

    sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
    // historyStack = new LinkedList<Link>();
    webview = (WebView) findViewById(R.id.webkit);

    WebSettings webSettings = webview.getSettings();
    webSettings.setJavaScriptEnabled(true);

    webSettings.setDomStorageEnabled(true);
    // webview.addJavascriptInterface(new WebViewDemoActivity(), "Android");
    // webview.getSettings().setJavaScriptEnabled(true);

    webview.getSettings().setBuiltInZoomControls(true);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
        // webview.getSettings().setPluginState(PluginState.ON);
        // webview.getSettings().setJavaScriptEnabled(true);
    } else {
        // IMPORTANT!! this method is no longer available since Android 4.3
        // so the code doesn't compile anymore
        // webview.getSettings().setPluginsEnabled(true);
    }

    // Internet

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    connected = false;
    if ((null != connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) && connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
            || (null != connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) && connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED)) {
        // we are connected to a network
        connected = true;
    }

    if (connected == false) {
        /*
         * Toast.makeText(Rss.this,
         * "Connect to internet and Restart Application",
         * Toast.LENGTH_SHORT).show();
         */
        webview.setVisibility(View.INVISIBLE);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(WebViewDemoActivity.this);

        // alertDialogBuilder.setTitle("Please connect to Internet");
        alertDialogBuilder.setMessage(
                "Through our app offers some offline features, in order to stay actively connected to the SmartWoman community in realtime, you need an internet connection, tap here to check your settings or wait until you have connection.");
        // set positive button: Yes message

        alertDialogBuilder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // cancel the alert box and put a Toast to the user

                startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
            }
        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        // show alert
        alertDialog.show();

    }

    // downloads
    // webview.setDownloadListener(new CustomDownloadListener());

    webview.setWebViewClient(new CustomWebViewClient());

    webview.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int progress) {

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {

        }

    });

    // http://stackoverflow.com/questions/2083909/android-webview-refusing-user-input
    webview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!v.hasFocus()) {
                    v.requestFocus();
                }
                break;
            }
            return false;
        }

    });

    if (reg == true) {
        if (Locale.getDefault().getLanguage().equals("es")) {

            webview.loadUrl("http://www.qa-msmartwoman.com/member/register");
            // webview.loadUrl("http://live-juice-guru.gotpantheon.com/user/login");
        } else {
            webview.loadUrl("http://www.qa-msmartwoman.com/member/register");
        }

        webview.requestFocus();
    } else {
        uhdj = sp.getString("your_int_key", "0");

        //   Log.e("Url is here ..............................", uhdj);
        // Welcome page loaded from assets directory
        if (Locale.getDefault().getLanguage().equals("es")) {

            webview.loadUrl(uhdj);
            // webview.loadUrl("http://live-juice-guru.gotpantheon.com/user/login");
        } else {
            webview.loadUrl(uhdj);
        }

        webview.requestFocus();
    }

}

From source file:aarddict.android.ArticleViewActivity.java

@Override
void initUI() {//from   w w w  .j av  a2s.  c om
    this.scrollPositionsH = Collections.synchronizedMap(new HashMap<Article, ScrollXY>());
    this.scrollPositionsV = Collections.synchronizedMap(new HashMap<Article, ScrollXY>());
    loadAssets();

    if (DeviceInfo.EINK_SCREEN) {
        useAnimation = false;
        setContentView(R.layout.eink_article_view);
        articleView = (ArticleView) findViewById(R.id.EinkArticleView);
        N2EpdController.n2MainActivity = this;
        EinkScreen.ResetController(2, articleView); // force full screen
                                                    // refresh when changing
                                                    // articles
    }
    // Setup animations only on non-eink screens
    else {
        useAnimation = true;
        fadeOutAnimation = new AlphaAnimation(1f, 0f);
        fadeOutAnimation.setDuration(600);
        fadeOutAnimation.setAnimationListener(new AnimationAdapter() {
            public void onAnimationEnd(Animation animation) {
                Button nextButton = (Button) findViewById(R.id.NextButton);
                nextButton.setVisibility(Button.GONE);
            }
        });

        getWindow().requestFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.article_view);
        articleView = (ArticleView) findViewById(R.id.ArticleView);
    }

    timer = new Timer();

    backItems = Collections.synchronizedList(new LinkedList<HistoryItem>());

    if (android.os.Build.VERSION.SDK_INT >= 11) {
        try {
            showFindDialogMethod = articleView.getClass().getMethod("showFindDialog", String.class,
                    boolean.class);
        } catch (NoSuchMethodException e1) {
            Log.d(TAG, "showFindDialog method not found");
        }

    }

    articleView.setOnScrollListener(new ArticleView.ScrollListener() {
        public void onScroll(int l, int t, int oldl, int oldt) {
            saveScrollPos(l, t);
        }
    });

    articleView.getSettings().setJavaScriptEnabled(true);
    articleView.addJavascriptInterface(new SectionMatcher(), "matcher");
    articleView.addJavascriptInterface(articleView, "scrollControl");

    articleView.setWebChromeClient(new WebChromeClient() {

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            Log.d(TAG + ".js", String.format("[%s]: %s", url, message));
            result.cancel();
            return true;
        }

        public void onProgressChanged(WebView view, int newProgress) {
            Log.d(TAG, "Progress: " + newProgress);
            setProgress(5000 + newProgress * 50);
        }
    });

    articleView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            Log.d(TAG, "Page finished: " + url);
            currentTask = null;
            String section = null;

            if (url.contains("#")) {
                LookupWord lookupWord = LookupWord.splitWord(url);
                section = lookupWord.section;
                if (backItems.size() > 0) {
                    HistoryItem currentHistoryItem = backItems.get(backItems.size() - 1);
                    HistoryItem h = new HistoryItem(currentHistoryItem);
                    h.article.section = section;
                    backItems.add(h);
                }
            } else if (backItems.size() > 0) {
                Article current = backItems.get(backItems.size() - 1).article;
                section = current.section;
            }
            if (!restoreScrollPos()) {
                goToSection(section);
            }
            updateNextButtonVisibility();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {
            Log.d(TAG, "URL clicked: " + url);
            String urlLower = url.toLowerCase();
            if (urlLower.startsWith("http://") || urlLower.startsWith("https://")
                    || urlLower.startsWith("ftp://") || urlLower.startsWith("sftp://")
                    || urlLower.startsWith("mailto:")) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(browserIntent);
            } else {
                if (currentTask == null) {
                    currentTask = new TimerTask() {
                        public void run() {
                            try {
                                Article currentArticle = backItems.get(backItems.size() - 1).article;
                                try {
                                    Iterator<Entry> currentIterator = dictionaryService.followLink(url,
                                            currentArticle.volumeId);
                                    List<Entry> result = new ArrayList<Entry>();
                                    while (currentIterator.hasNext() && result.size() < 20) {
                                        result.add(currentIterator.next());
                                    }
                                    showNext(new HistoryItem(result));
                                } catch (ArticleNotFound e) {
                                    showMessage(getString(R.string.msgArticleNotFound, e.word.toString()));
                                }
                            } catch (Exception e) {
                                StringBuilder msgBuilder = new StringBuilder(
                                        "There was an error following link ").append("\"").append(url)
                                                .append("\"");
                                if (e.getMessage() != null) {
                                    msgBuilder.append(": ").append(e.getMessage());
                                }
                                final String msg = msgBuilder.toString();
                                Log.e(TAG, msg, e);
                                showError(msg);
                            }
                        }
                    };
                    try {
                        timer.schedule(currentTask, 0);
                    } catch (Exception e) {
                        Log.d(TAG, "Failed to schedule task", e);
                    }
                }
            }
            return true;
        }
    });
    final Button nextButton = (Button) findViewById(R.id.NextButton);
    nextButton.getBackground().setAlpha(180);
    nextButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (nextButton.getVisibility() == View.VISIBLE) {
                updateNextButtonVisibility();
                nextArticle();
                updateNextButtonVisibility();
            }
        }
    });
    articleView.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            updateNextButtonVisibility();
            return false;
        }
    });

    setProgressBarVisibility(true);
}

From source file:com.guodong.sun.guodong.activity.ZhiHuDetailActivity.java

private void initWebView() {
    mWebView.setScrollbarFadingEnabled(true);
    //js/*www.j a  v  a  2s  .  c  om*/
    mWebView.getSettings().setJavaScriptEnabled(true);
    //,????
    mWebView.getSettings().setBuiltInZoomControls(false);
    //
    mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    //?DOM storage API
    mWebView.getSettings().setDomStorageEnabled(true);
    //?application Cache
    mWebView.getSettings().setAppCacheEnabled(true);
    mWebView.getSettings().setAppCachePath(getCacheDir().getAbsolutePath() + "/webViewCache");
    mWebView.getSettings().setBlockNetworkImage(true);
    mWebView.getSettings().setLoadWithOverviewMode(true);
    mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    mWebView.setWebChromeClient(new WebChromeClient());
}