Example usage for android.webkit WebView getSettings

List of usage examples for android.webkit WebView getSettings

Introduction

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

Prototype

public WebSettings getSettings() 

Source Link

Document

Gets the WebSettings object used to control the settings for this WebView.

Usage

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

@ReactProp(name = "userAgent")
public void setUserAgent(WebView view, @Nullable String userAgent) {
    if (userAgent != null) {
        // TODO(8496850): Fix incorrect behavior when property is unset (uA == null)
        view.getSettings().setUserAgentString(userAgent);
    }//from   w ww. ja  va2s  .  c o  m
}

From source file:org.liberty.android.fantastischmemo.downloader.google.GoogleOAuth2AccessCodeRetrievalFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final View v = inflater.inflate(R.layout.oauth_login_layout, container, false);
    final WebView webview = (WebView) v.findViewById(R.id.login_page);
    final View loadingText = v.findViewById(R.id.auth_page_load_text);
    final View progressDialog = v.findViewById(R.id.auth_page_load_progress);
    final LinearLayout ll = (LinearLayout) v.findViewById(R.id.ll);

    // We have to set up the dialog's webview size manually or the webview will be zero size.
    // This should be a bug of Android.
    Rect displayRectangle = new Rect();
    Window window = mActivity.getWindow();
    window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);

    ll.setMinimumWidth((int) (displayRectangle.width() * 0.9f));
    ll.setMinimumHeight((int) (displayRectangle.height() * 0.8f));

    webview.getSettings().setJavaScriptEnabled(true);
    try {/* ww w .jav  a2  s .  c  om*/
        String uri = String.format(
                "https://accounts.google.com/o/oauth2/auth?client_id=%s&response_type=%s&redirect_uri=%s&scope=%s",
                URLEncoder.encode(AMEnv.GOOGLE_CLIENT_ID, "UTF-8"), URLEncoder.encode("code", "UTF-8"),
                URLEncoder.encode(AMEnv.GOOGLE_REDIRECT_URI, "UTF-8"),
                URLEncoder.encode(AMEnv.GDRIVE_SCOPE, "UTF-8"));
        webview.loadUrl(uri);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    // This is workaround to show input on some android version.
    webview.requestFocus(View.FOCUS_DOWN);
    webview.setOnTouchListener(new View.OnTouchListener() {
        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;
        }
    });

    webview.setWebViewClient(new WebViewClient() {
        private boolean authenticated = false;

        @Override
        public void onPageFinished(WebView view, String url) {
            loadingText.setVisibility(View.GONE);
            progressDialog.setVisibility(View.GONE);
            webview.setVisibility(View.VISIBLE);
            if (authenticated == true) {
                return;
            }
            String code = getAuthCodeFromUrl(url);
            String error = getErrorFromUrl(url);
            if (error != null) {
                authCodeReceiveListener.onAuthCodeError(error);
                authenticated = true;
                dismiss();
            }
            if (code != null) {
                authenticated = true;
                authCodeReceiveListener.onAuthCodeReceived(code);
                dismiss();
            }
        }
    });
    return v;
}

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

@ReactProp(name = "mixedContentMode")
public void setMixedContentMode(WebView view, @Nullable String mixedContentMode) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        if (mixedContentMode == null || "never".equals(mixedContentMode)) {
            view.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
        } else if ("always".equals(mixedContentMode)) {
            view.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        } else if ("compatibility".equals(mixedContentMode)) {
            view.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }//  w  w  w  . j a v  a2s .  c om
    }
}

From source file:com.rsltc.profiledata.main.MainActivity.java

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

    Button loginButton = (Button) findViewById(R.id.button);
    loginButton.setOnClickListener(new View.OnClickListener() {
        @Override//from ww  w.j  a  va  2  s  .c o  m
        public void onClick(View v) {
            try {
                AlertDialog.Builder alert = new AlertDialog.Builder(thisActivity);
                alert.setTitle("Title here");

                StringBuilder query = new StringBuilder();

                query.append("redirect_uri=" + URLEncoder.encode(redirectUri, "utf-8"));
                query.append("&client_id=" + URLEncoder.encode(clientId, "utf-8"));
                query.append("&scope=" + URLEncoder.encode(scopes, "utf-8"));

                query.append("&response_type=code");
                URI uri = new URI("https://login.live.com/oauth20_authorize.srf?" + query.toString());

                URL url = uri.toURL();

                final WebView wv = new WebView(thisActivity);

                WebSettings webSettings = wv.getSettings();
                webSettings.setJavaScriptEnabled(true);
                wv.loadUrl(url.toString());
                wv.setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String location) {
                        Log.e(TAG, location);
                        // TODO: extract to method
                        try {
                            URL url = new URL(location);

                            if (url.getPath().equalsIgnoreCase("/oauth20_desktop.srf")) {
                                System.out.println("Dit werkt al!");
                                System.out.println(url.getQuery());
                                Map<String, List<String>> result = splitQuery(url);
                                if (result.containsKey("code")) {
                                    System.out.println("bevat code");
                                    if (result.containsKey("error")) {
                                        System.out.println(String.format("{0}\r\n{1}", result.get("error"),
                                                result.get("errorDesc")));
                                    }
                                    System.out.println(result.get("code").get(0));
                                    String tokenError = GetToken(result.get("code").get(0), false);
                                    if (tokenError == null || "".equals(tokenError)) {
                                        System.out.println("Successful sign-in!");
                                        Log.e(TAG, "Successful sign-in!");
                                    } else {
                                        Log.e(TAG, "tokenError: " + tokenError);
                                    }
                                } else {
                                    System.out.println("Successful sign-out!");
                                }
                            }
                        } catch (IOException | URISyntaxException e) {
                            e.printStackTrace();
                        }

                        view.loadUrl(location);

                        return true;
                    }
                });
                LinearLayout linearLayout = new LinearLayout(thisActivity);
                linearLayout.setMinimumHeight(500);
                ArrayList<View> views = new ArrayList<View>();
                views.add(wv);
                linearLayout.addView(wv);
                EditText text = new EditText(thisActivity);
                text.setVisibility(View.GONE);
                linearLayout.addView(text);
                alert.setView(linearLayout);
                alert.setNegativeButton("Close", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.dismiss();
                    }
                });
                alert.show();
            } catch (Exception e) {
                Log.e(TAG, "dd");
            }
        }
    });
    Button showProfile = (Button) findViewById(R.id.button2);
    showProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showProfile();
        }
    });
    Button showSummmary = (Button) findViewById(R.id.button3);
    showSummmary.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showSummaries();
        }
    });

    if (savedInstanceState != null)

    {
        authInProgress = savedInstanceState.getBoolean(AUTH_PENDING);
    }

    buildFitnessClient();
}

From source file:com.nestlabs.sdk.NestAuthActivity.java

@Override
@SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.nest_auth_webview_layout);

    WebView clientWebView = (WebView) findViewById(R.id.auth_webview);
    mProgressBar = (ProgressBar) findViewById(R.id.webview_progress);
    mNestConfig = getIntent().getParcelableExtra(KEY_CLIENT_METADATA);

    // If any args are empty, they are invalid and we should finish.
    if (mNestConfig == null || Utils.isAnyEmpty(mNestConfig.getRedirectURL(), mNestConfig.getClientID(),
            mNestConfig.getStateValue())) {
        finishWithResult(RESULT_CANCELED, null);
        return;//from   ww w  .j av a 2 s . com
    }

    mHttpClient = new OkHttpClient();

    clientWebView.setWebChromeClient(new ProgressChromeClient());
    clientWebView.setWebViewClient(new RedirectClient());

    String url = String.format(NestAPI.CLIENT_CODE_URL, mNestConfig.getClientID(), mNestConfig.getStateValue());
    WebSettings webSettings = clientWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    clientWebView.loadUrl(url);
}

From source file:org.esupportail.nfctagdroid.NfcTacDroidActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ESUP_NFC_TAG_SERVER_URL = getEsupNfcTagServerUrl(getApplicationContext());
    //To keep session for desfire async requests
    CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
    LocalStorage.getInstance(getApplicationContext());
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getApplicationContext()));
    setContentView(R.layout.activity_main);
    mAdapter = NfcAdapter.getDefaultAdapter(this);
    checkHardware(mAdapter);//from   w  w  w.  j  ava  2  s.  c om
    localStorageDBHelper = LocalStorage.getInstance(this.getApplicationContext());
    String numeroId = localStorageDBHelper.getValue("numeroId");
    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String imei = telephonyManager.getDeviceId();
    url = ESUP_NFC_TAG_SERVER_URL + "/nfc-index?numeroId=" + numeroId + "&imei=" + imei + "&macAddress="
            + getMacAddr() + "&apkVersion=" + getApkVersion();
    view = (WebView) this.findViewById(R.id.webView);
    view.clearCache(true);
    view.addJavascriptInterface(new LocalStorageJavaScriptInterface(this.getApplicationContext()),
            "AndroidLocalStorage");
    view.addJavascriptInterface(new AndroidJavaScriptInterface(this.getApplicationContext()), "Android");

    view.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int progress) {
            if (progress == 100) {
                AUTH_TYPE = localStorageDBHelper.getValue("authType");
            }
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            log.info("Webview console message : " + consoleMessage.message());
            return false;
        }

    });

    view.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            view.reload();
            return true;
        }
    });
    view.getSettings().setAllowContentAccess(true);
    WebSettings webSettings = view.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webSettings.setDatabasePath(this.getFilesDir().getParentFile().getPath() + "/databases/");

    view.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
        }

    });

    view.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
        }
    });

    view.loadUrl(url);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

From source file:com.openerp.support.listview.OEListViewAdapter.java

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    viewRow = convertView;//from w w  w.  j ava  2  s .  c o  m
    parentView = parent;
    LayoutInflater inflater = ((MainActivity) context).getLayoutInflater();
    if (viewRow == null) {
        viewRow = inflater.inflate(this.resource_id, parent, false);
    }
    row = this.rows.get(position);
    rowdata = row.getRow_data();
    for (final Integer control_id : controlClickHandler.keySet()) {
        viewRow.findViewById(control_id).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                controlClickHandler.get(control_id).controlClicked(position, rows.get(position), viewRow);
            }
        });
    }

    for (int i = 0; i < this.to.length; i++) {
        final String key = from[i];
        if (booleanEvents.contains(from[i])) {
            handleBinaryBackground(row.getRow_id(), key, to[i], viewRow, position);
        } else if (backgroundChange.containsKey(key)) {
            String backFlag = rowdata.get(key).toString();
            if (!backFlag.equals("false")) {
                backFlag = "true";
            }
            int color = backgroundChange.get(key).get(backFlag);
            viewRow.findViewById(this.to[i]).setBackgroundColor(color);
            continue;
        } else if (imageCols.contains(from[i])) {
            String data = rowdata.get(from[i]).toString();
            if (!data.equals("false")) {
                ImageView imgView = (ImageView) viewRow.findViewById(this.to[i]);
                imgView.setImageBitmap(Base64Helper.getBitmapImage(context, data));
            }
        } else {
            TextView txvObj = null;
            WebView webview = null;
            if (!webViewControls.containsKey(this.from[i])) {
                txvObj = (TextView) viewRow.findViewById(this.to[i]);
            } else {
                if (webViewControls.get(this.from[i])) {
                    webview = (WebView) viewRow.findViewById(this.to[i]);
                    webview.getSettings().setJavaScriptEnabled(true);
                    webview.getSettings().setBuiltInZoomControls(true);
                } else {
                    txvObj = (TextView) viewRow.findViewById(this.to[i]);
                }
            }

            String key_col = this.from[i];
            String alt_key_col = key_col;
            if (key_col.contains("|")) {
                String[] splits = key_col.split("\\|");
                key_col = splits[0];
                alt_key_col = splits[1];
            }
            String data = rowdata.get(key_col).toString();
            if (data.equals("false") || TextUtils.isEmpty(data)) {
                data = rowdata.get(alt_key_col).toString();
            }
            if (this.cleanColumn.contains(key_col)) {
                data = HTMLHelper.htmlToString(data);
            }

            if (datecols.contains(key_col)) {
                if (date_format != null) {
                    data = OEDate.getDate(data, TimeZone.getDefault().getID(), date_format);
                } else {
                    data = OEDate.getDate(data, TimeZone.getDefault().getID());
                }
            }

            if (!data.equals("false")) {
                try {
                    StringBuffer inputdata = new StringBuffer();
                    JSONArray tmpData = new JSONArray(data);
                    for (int k = 0; k < tmpData.length(); k++) {
                        if (tmpData.get(k) instanceof JSONArray) {
                            if (tmpData.getJSONArray(k).length() == 2) {
                                inputdata.append(tmpData.getJSONArray(k).getString(1));
                                inputdata.append(",");
                            }
                        } else {
                            inputdata.append(tmpData.getString(0));
                            inputdata.append(",");
                        }
                    }
                    int index = inputdata.lastIndexOf(",");
                    if (index > 0) {
                        inputdata.deleteCharAt(index);
                    }
                    txvObj.setText(inputdata.toString());
                } catch (Exception e) {
                    if (this.toHtml.contains(key_col)) {
                        if (webViewControls.get(this.from[i])) {
                            String customHtml = data;
                            webview.loadData(customHtml, "text/html", "UTF-8");
                        } else {
                            txvObj.setText(HTMLHelper.stringToHtml(data));
                        }
                    } else {
                        txvObj.setText(data);
                    }

                }

            } else {
                txvObj.setText("");
            }
        }
    }
    if (this.canChangeBackground && !viewRow.isSelected()) {
        boolean flag = Boolean.parseBoolean(rowdata.get(conditionKey).toString());
        if (flag) {
            viewRow.setBackgroundResource(colors[1]);

        } else {
            viewRow.setBackgroundResource(colors[0]);
        }
    }
    if (viewListener != null) {
        viewRow = viewListener.listViewOnCreateListener(position, viewRow, this.rows.get(position));
    }

    return viewRow;
}

From source file:io.github.hidroh.materialistic.OfflineWebActivity.java

@SuppressWarnings("ConstantConditions")
@Override/*www.j  a  v  a 2 s.  c om*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String url = getIntent().getStringExtra(EXTRA_URL);
    if (TextUtils.isEmpty(url)) {
        finish();
        return;
    }
    setTitle(url);
    setContentView(R.layout.activity_offline_web);
    final NestedScrollView scrollView = (NestedScrollView) findViewById(R.id.nested_scroll_view);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setOnClickListener(v -> scrollView.smoothScrollTo(0, 0));
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayOptions(
            ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_TITLE);
    getSupportActionBar().setSubtitle(R.string.offline);
    final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress);
    final WebView webView = (WebView) findViewById(R.id.web_view);
    webView.setBackgroundColor(Color.TRANSPARENT);
    webView.setWebViewClient(new AdBlockWebViewClient(Preferences.adBlockEnabled(this)) {
        @Override
        public void onPageFinished(WebView view, String url) {
            setTitle(view.getTitle());
        }
    });
    webView.setWebChromeClient(new CacheableWebView.ArchiveClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            progressBar.setVisibility(View.VISIBLE);
            progressBar.setProgress(newProgress);
            if (newProgress == 100) {
                progressBar.setVisibility(View.GONE);
                webView.setBackgroundColor(Color.WHITE);
                webView.setVisibility(View.VISIBLE);
            }
        }
    });
    AppUtils.toggleWebViewZoom(webView.getSettings(), true);
    webView.loadUrl(url);
}

From source file:com.microsoft.windowsazure.mobileservices.authentication.LoginManager.java

/**
 * Creates the UI for the interactive authentication process
 *
 * @param startUrl The initial URL for the authentication process
 * @param endUrl   The final URL for the authentication process
 * @param context  The context used to create the authentication dialog
 * @param callback Callback to invoke when the authentication process finishes
 *//* w  w  w  .  java 2 s .  co  m*/
private void showLoginUIInternal(final String startUrl, final String endUrl, final Context context,
        LoginUIOperationCallback callback) {
    if (startUrl == null || startUrl == "") {
        throw new IllegalArgumentException("startUrl can not be null or empty");
    }

    if (endUrl == null || endUrl == "") {
        throw new IllegalArgumentException("endUrl can not be null or empty");
    }

    if (context == null) {
        throw new IllegalArgumentException("context can not be null");
    }

    final LoginUIOperationCallback externalCallback = callback;
    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    // Create the Web View to show the login page
    final WebView wv = new WebView(context);
    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialog) {
            if (externalCallback != null) {
                externalCallback.onCompleted(null, new MobileServiceException("User Canceled"));
            }
        }
    });

    wv.getSettings().setJavaScriptEnabled(true);

    DisplayMetrics displaymetrics = new DisplayMetrics();
    ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int webViewHeight = displaymetrics.heightPixels - 100;

    wv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, webViewHeight));

    wv.requestFocus(View.FOCUS_DOWN);
    wv.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) {
                if (!view.hasFocus()) {
                    view.requestFocus();
                }
            }

            return false;
        }
    });

    // Create a LinearLayout and add the WebView to the Layout
    LinearLayout layout = new LinearLayout(context);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(wv);

    // Add a dummy EditText to the layout as a workaround for a bug
    // that prevents showing the keyboard for the WebView on some devices
    EditText dummyEditText = new EditText(context);
    dummyEditText.setVisibility(View.GONE);
    layout.addView(dummyEditText);

    // Add the layout to the dialog
    builder.setView(layout);

    final AlertDialog dialog = builder.create();

    wv.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // If the URL of the started page matches with the final URL
            // format, the login process finished

            if (isFinalUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(url, null);
                }

                dialog.dismiss();
            }

            super.onPageStarted(view, url, favicon);
        }

        // Checks if the given URL matches with the final URL's format
        private boolean isFinalUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(endUrl);
        }

        // Checks if the given URL matches with the start URL's format
        private boolean isStartUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(startUrl);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (isStartUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(null, new MobileServiceException(
                            "Logging in with the selected authentication provider is not enabled"));
                }

                dialog.dismiss();
            }
        }
    });

    wv.loadUrl(startUrl);
    dialog.show();
}

From source file:com.mb.android.MainActivity.java

@Override
protected CordovaWebViewEngine makeWebViewEngine() {

    Context context = getApplicationContext();
    CordovaWebViewEngine engine;/*  w ww . j a  v  a  2  s . c  om*/

    final ILogger logger = getLogger();

    if (enableSystemWebView()) {

        engine = new SystemWebViewEngine(new MySystemWebView(this, logger), preferences);
        WebView webkitView = (WebView) engine.getView();
        webkitView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView = new NativeWebView(webkitView);

    } else {
        engine = new MyXWalkWebViewEngine(this, preferences, this);
        XWalkCordovaView xView = (XWalkCordovaView) engine.getView();
        webView = new CrosswalkWebView(xView);
    }

    jsonSerializer = new GsonJsonSerializer();

    iapManager = new IapManager(context, webView, logger);
    ApiClientBridge apiClientBridge = new ApiClientBridge(context, logger, webView, jsonSerializer);
    httpClient = apiClientBridge.httpClient;

    return engine;
}