Example usage for android.webkit WebSettings getUserAgentString

List of usage examples for android.webkit WebSettings getUserAgentString

Introduction

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

Prototype

public abstract String getUserAgentString();

Source Link

Document

Gets the WebView's user-agent string.

Usage

From source file:Main.java

public static String getDefaultUserAgentString(Context context) {
    //      String userAgent = System.getProperty("http.agent");
    try {/* ww w  .  j ava 2  s . c om*/
        Constructor<WebSettings> constructor = WebSettings.class.getDeclaredConstructor(Context.class,
                WebView.class);
        constructor.setAccessible(true);
        try {
            WebSettings settings = constructor.newInstance(context, null);
            return settings.getUserAgentString();
        } finally {
            constructor.setAccessible(false);
        }
    } catch (Exception e) {
        return new WebView(context).getSettings().getUserAgentString();
    }
}

From source file:Main.java

public static String getUserAgentString(Context context) {
    if (userAgent == null) {
        try {//  ww w  .ja v  a  2  s.c  om
            Constructor<WebSettings> constructor = WebSettings.class.getDeclaredConstructor(Context.class,
                    WebView.class);
            constructor.setAccessible(true);
            try {
                WebSettings settings = constructor.newInstance(context, null);
                userAgent = settings.getUserAgentString();
            } finally {
                constructor.setAccessible(false);
            }
        } catch (Exception e) {
            userAgent = new WebView(context).getSettings().getUserAgentString();
        }
    }
    return userAgent;
}

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

@SuppressLint("SetJavaScriptEnabled")
private static void prepareWebViewSettings(WebSettings settings) {
    settings.setUserAgentString(settings.getUserAgentString() + MAGIC_USER_AGENT);
    settings.setJavaScriptEnabled(true);
    settings.setSupportMultipleWindows(false);
    settings.setSaveFormData(false);/*from   w  w w  .ja v  a2  s.c o  m*/
    settings.setAllowFileAccess(false);
    settings.setDatabaseEnabled(false);
    settings.setNeedInitialFocus(false);
    settings.setUseWideViewPort(false);
    settings.setSupportZoom(false);
    settings.setJavaScriptCanOpenWindowsAutomatically(false);
}

From source file:com.llkj.cm.restfull.network.NetworkConnection.java

/**
 * By default the user agent is empty. If you want to use the standard Android user agent, call this method before using the
 * <code>retrieveResponseFromService</code> methods
 * //from   w  ww  .  j  av a2 s  .c  o m
 * @param context The context
 */
public static void generateDefaultUserAgent(final Context context) {
    if (sDefaultUserAgent != null) {
        return;
    }

    try {
        Constructor<WebSettings> constructor = WebSettings.class.getDeclaredConstructor(Context.class,
                WebView.class);
        constructor.setAccessible(true);
        try {
            WebSettings settings = constructor.newInstance(context, null);
            sDefaultUserAgent = settings.getUserAgentString();
        } finally {
            constructor.setAccessible(false);
        }
    } catch (Exception e) {
        if (Thread.currentThread().getName().equalsIgnoreCase("main")) {
            WebView webview = new WebView(context);
            sDefaultUserAgent = webview.getSettings().getUserAgentString();
        } else {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    Looper.prepare();
                    WebView webview = new WebView(context);
                    sDefaultUserAgent = webview.getSettings().getUserAgentString();
                    Looper.loop();
                }
            };
            thread.start();
        }
    }
}

From source file:com.linkbubble.util.Util.java

/**
 * From http://stackoverflow.com/a/5261472/328679
 *///from  ww w  .  j a  v a  2 s.  c  o  m
public static String getDefaultUserAgentString(Context context) {
    if (Build.VERSION.SDK_INT >= 17) {
        return WebSettings.getDefaultUserAgent(context);
    }

    try {
        Constructor<WebSettings> constructor = WebSettings.class.getDeclaredConstructor(Context.class,
                WebView.class);
        constructor.setAccessible(true);
        try {
            WebSettings settings = constructor.newInstance(context, null);
            return settings.getUserAgentString();
        } finally {
            constructor.setAccessible(false);
        }
    } catch (Exception e) {
        return Config.sIsTablet ? Constant.USER_AGENT_CHROME_TABLET : Constant.USER_AGENT_CHROME_PHONE;
    }
}

From source file:net.wequick.small.webkit.WebView.java

private void initSettings() {
    WebSettings webSettings = this.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setUserAgentString(webSettings.getUserAgentString() + " Native");
    this.addJavascriptInterface(new SmallJsBridge(), "_Small");

    this.setWebChromeClient(new WebChromeClient() {
        @Override/*from  w ww. ja va 2  s.  c  om*/
        public void onReceivedTitle(android.webkit.WebView view, String title) {
            // Call if html title is set
            super.onReceivedTitle(view, title);
            mTitle = title;
            WebActivity activity = (WebActivity) WebViewPool.getContext(view);
            if (activity != null) {
                activity.setTitle(title);
            }
            // May receive head meta at the same time
            initMetas();
        }

        @Override
        public boolean onJsAlert(android.webkit.WebView view, String url, String message,
                final android.webkit.JsResult result) {
            Context context = WebViewPool.getContext(view);
            if (context == null)
                return false;

            AlertDialog.Builder dlg = new AlertDialog.Builder(context);
            dlg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmed = true;
                    result.confirm();
                }
            });
            dlg.setMessage(message);
            AlertDialog alert = dlg.create();
            alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (!mConfirmed) {
                        result.cancel();
                    }
                }
            });
            mConfirmed = false;
            alert.show();
            return true;
        }

        @Override
        public boolean onJsConfirm(android.webkit.WebView view, String url, String message,
                final android.webkit.JsResult result) {
            Context context = WebViewPool.getContext(view);
            AlertDialog.Builder dlg = new AlertDialog.Builder(context);
            dlg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmed = true;
                    result.confirm();
                }
            });
            dlg.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmed = true;
                    result.cancel();
                }
            });
            dlg.setMessage(message);
            AlertDialog alert = dlg.create();
            alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (!mConfirmed) {
                        result.cancel();
                    }
                }
            });
            mConfirmed = false;
            alert.show();
            return true;
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            String msg = consoleMessage.message();
            if (msg == null)
                return false;
            Uri uri = Uri.parse(msg);
            if (uri != null && null != uri.getScheme() && uri.getScheme().equals(SMALL_SCHEME)) {
                String host = uri.getHost();
                String ret = uri.getQueryParameter(SMALL_QUERY_KEY_RET);
                if (host.equals(SMALL_HOST_POP)) {
                    WebActivity activity = (WebActivity) WebViewPool.getContext(WebView.this);
                    activity.finish(ret);
                } else if (host.equals(SMALL_HOST_EXEC)) {
                    if (mOnResultListener != null) {
                        mOnResultListener.onResult(ret);
                    }
                }
                return true;
            }
            Log.d(consoleMessage.sourceId(),
                    "line" + consoleMessage.lineNumber() + ": " + consoleMessage.message());
            return true;
        }

        @Override
        public void onCloseWindow(android.webkit.WebView window) {
            super.onCloseWindow(window);
            close(new OnResultListener() {
                @Override
                public void onResult(String ret) {
                    if (ret.equals("false"))
                        return;

                    WebActivity activity = (WebActivity) WebViewPool.getContext(WebView.this);
                    activity.finish(ret);
                }
            });
        }
    });

    this.setWebViewClient(new android.webkit.WebViewClient() {

        private final String ANCHOR_SCHEME = "anchor";

        @Override
        public boolean shouldOverrideUrlLoading(android.webkit.WebView view, String url) {
            if (mLoadingUrl != null && mLoadingUrl.equals(url)) {
                // reload by window.location.reload or something
                return super.shouldOverrideUrlLoading(view, url);
            }

            Boolean hasStarted = mHasStartedUrl.get(url);
            if (hasStarted != null && hasStarted) {
                // location redirected before page finished
                return super.shouldOverrideUrlLoading(view, url);
            }

            HitTestResult hit = view.getHitTestResult();
            if (hit != null) {
                Uri uri = Uri.parse(url);
                if (uri.getScheme().equals(ANCHOR_SCHEME)) {
                    // Scroll to anchor
                    int anchorY = Integer.parseInt(uri.getHost());
                    view.scrollTo(0, anchorY);
                } else {
                    Small.openUri(uri, WebViewPool.getContext(view));
                }
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mHasStartedUrl.put(url, true);

            if (mLoadingUrl != null && mLoadingUrl.equals(url)) {
                // reload by window.location.reload or something
                mInjected = false;
            }
            if (sWebViewClient != null && url.equals(mLoadingUrl)) {
                sWebViewClient.onPageStarted(WebViewPool.getContext(view), (WebView) view, url, favicon);
            }
        }

        @Override
        public void onPageFinished(android.webkit.WebView view, String url) {
            super.onPageFinished(view, url);
            mHasStartedUrl.remove(url);

            HitTestResult hit = view.getHitTestResult();
            if (hit != null && hit.getType() == HitTestResult.SRC_ANCHOR_TYPE) {
                // Triggered by user clicked
                Uri uri = Uri.parse(url);
                String anchor = uri.getFragment();
                if (anchor != null) {
                    // If is an anchor, calculate the content offset by DOM
                    // and call native to adjust WebView's offset
                    view.loadUrl(JS_PREFIX + "var y=document.body.scrollTop;"
                            + "var e=document.getElementsByName('" + anchor + "')[0];" + "while(e){"
                            + "y+=e.offsetTop-e.scrollTop+e.clientTop;e=e.offsetParent;}" + "location='"
                            + ANCHOR_SCHEME + "://'+y;");
                }
            }

            if (!mInjected) {
                // Re-inject Small Js
                loadJs(SMALL_INJECT_JS);
                initMetas();
                mInjected = true;
            }

            if (sWebViewClient != null && url.equals(mLoadingUrl)) {
                sWebViewClient.onPageFinished(WebViewPool.getContext(view), (WebView) view, url);
            }
        }

        @Override
        public void onReceivedError(android.webkit.WebView view, int errorCode, String description,
                String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            Log.e("Web", "error: " + description);
            if (sWebViewClient != null && failingUrl.equals(mLoadingUrl)) {
                sWebViewClient.onReceivedError(WebViewPool.getContext(view), (WebView) view, errorCode,
                        description, failingUrl);
            }
        }
    });
}

From source file:net.olejon.spotcommander.WebViewActivity.java

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

    // Google API client
    mGoogleApiClient = new GoogleApiClient.Builder(mContext).addApiIfAvailable(Wearable.API).build();

    // Allow landscape?
    if (!mTools.allowLandscape())
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    // Hide status bar?
    if (mTools.getDefaultSharedPreferencesBoolean("HIDE_STATUS_BAR"))
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

    // Power manager
    final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

    //noinspection deprecation
    mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "wakeLock");

    // Settings/*from  w  w w  . j a  va 2 s.co m*/
    mTools.setSharedPreferencesBoolean("CAN_CLOSE_COVER", false);

    // Current network
    mCurrentNetwork = mTools.getCurrentNetwork();

    // Computer
    final long computerId = mTools.getSharedPreferencesLong("LAST_COMPUTER_ID");

    final String[] computer = mTools.getComputer(computerId);

    final String uri = computer[0];
    final String username = computer[1];
    final String password = computer[2];

    // Layout
    setContentView(R.layout.activity_webview);

    // Status bar color
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mStatusBarPrimaryColor = getWindow().getStatusBarColor();
        mStatusBarCoverArtColor = mStatusBarPrimaryColor;
    }

    // Notification
    mPersistentNotificationIsSupported = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN);

    if (mPersistentNotificationIsSupported) {
        final Intent launchActivityIntent = new Intent(mContext, MainActivity.class);
        launchActivityIntent.setAction("android.intent.action.MAIN");
        launchActivityIntent.addCategory("android.intent.category.LAUNCHER");
        mLaunchActivityPendingIntent = PendingIntent.getActivity(mContext, 0, launchActivityIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent hideIntent = new Intent(mContext, RemoteControlIntentService.class);
        hideIntent.setAction("hide_notification");
        hideIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mHidePendingIntent = PendingIntent.getService(mContext, 0, hideIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent previousIntent = new Intent(mContext, RemoteControlIntentService.class);
        previousIntent.setAction("previous");
        previousIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mPreviousPendingIntent = PendingIntent.getService(mContext, 0, previousIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent playPauseIntent = new Intent(mContext, RemoteControlIntentService.class);
        playPauseIntent.setAction("play_pause");
        playPauseIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mPlayPausePendingIntent = PendingIntent.getService(mContext, 0, playPauseIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent nextIntent = new Intent(mContext, RemoteControlIntentService.class);
        nextIntent.setAction("next");
        nextIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mNextPendingIntent = PendingIntent.getService(mContext, 0, nextIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent volumeDownIntent = new Intent(mContext, RemoteControlIntentService.class);
        volumeDownIntent.setAction("adjust_spotify_volume_down");
        volumeDownIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mVolumeDownPendingIntent = PendingIntent.getService(mContext, 0, volumeDownIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent volumeUpIntent = new Intent(mContext, RemoteControlIntentService.class);
        volumeUpIntent.setAction("adjust_spotify_volume_up");
        volumeUpIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mVolumeUpPendingIntent = PendingIntent.getService(mContext, 0, volumeUpIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        mNotificationManager = NotificationManagerCompat.from(mContext);
        mNotificationBuilder = new NotificationCompat.Builder(mContext);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
            mNotificationBuilder.setPriority(Notification.PRIORITY_MAX);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mNotificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
            mNotificationBuilder.setCategory(Notification.CATEGORY_TRANSPORT);
        }
    }

    // Web view
    mWebView = (WebView) findViewById(R.id.webview_webview);

    mWebView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.background));
    mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);

    mWebView.setWebViewClient(new WebViewClient() {
        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && !url.contains(uri)
                    && !url.contains("olejon.net/code/spotcommander/api/1/spotify/")
                    && !url.contains("accounts.spotify.com/") && !url.contains("facebook.com/")) {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));

                return true;
            }

            return false;
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view, @NonNull HttpAuthHandler handler, String host,
                String realm) {
            if (handler.useHttpAuthUsernamePassword()) {
                handler.proceed(username, password);
            } else {
                handler.cancel();

                mWebView.stopLoading();

                mTools.showToast(getString(R.string.webview_authentication_failed), 1);

                mTools.navigateUp(mActivity);
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest webResourceRequest,
                WebResourceError webResourceError) {
            mWebView.stopLoading();

            mTools.showToast(getString(R.string.webview_error), 1);

            mTools.navigateUp(mActivity);
        }

        @Override
        public void onReceivedSslError(WebView view, @NonNull SslErrorHandler handler, SslError error) {
            handler.cancel();

            mWebView.stopLoading();

            new MaterialDialog.Builder(mContext).title(R.string.webview_dialog_ssl_error_title)
                    .content(getString(R.string.webview_dialog_ssl_error_message))
                    .positiveText(R.string.webview_dialog_ssl_error_positive_button)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog materialDialog,
                                @NonNull DialogAction dialogAction) {
                            finish();
                        }
                    }).contentColorRes(R.color.black).show();
        }
    });

    // User agent
    mProjectVersionName = mTools.getProjectVersionName();

    final String uaAppend1 = (!username.equals("") && !password.equals("")) ? "AUTHENTICATION_ENABLED " : "";
    final String uaAppend2 = (mTools.getSharedPreferencesBoolean("WEAR_CONNECTED")) ? "WEAR_CONNECTED " : "";
    final String uaAppend3 = (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT
            && !mTools.getDefaultSharedPreferencesBoolean("HARDWARE_ACCELERATED_ANIMATIONS"))
                    ? "DISABLE_CSSTRANSITIONS DISABLE_CSSTRANSFORMS3D "
                    : "";

    // Web settings
    final WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setSupportZoom(false);
    webSettings.setUserAgentString(getString(R.string.webview_user_agent, webSettings.getUserAgentString(),
            mProjectVersionName, uaAppend1, uaAppend2, uaAppend3));

    // Load app
    if (savedInstanceState != null) {
        mWebView.restoreState(savedInstanceState);
    } else {
        mWebView.loadUrl(uri);
    }

    // JavaScript interface
    mWebView.addJavascriptInterface(new JavaScriptInterface(), "Android");
}

From source file:com.air.mobilebrowser.BrowserActivity.java

/** 
 * Configure a webview to use the activity as
 * its client, and update its settings with 
 * the desired parameters for the activity.
 * @param webView the webview to configure.
 *///from  w  w w  .  java  2  s  .com
private void configureWebView(WebView webView) {
    webView.clearCache(true);
    webView.setWebViewClient(new SecureWebClient(this));

    WebSettings settings = mWebView.getSettings();
    settings.setBuiltInZoomControls(true);
    settings.setJavaScriptEnabled(true);
    //      settings.setPluginState(PluginState.ON_DEMAND);
    settings.setPluginState(PluginState.ON);
    settings.setAllowFileAccess(true);
    settings.setAllowContentAccess(true);
    settings.setSaveFormData(false);
    settings.setSavePassword(false);
    webView.clearFormData();
    settings.setDomStorageEnabled(true);
    String defaultUserAgent = settings.getUserAgentString();

    StringBuilder sb = new StringBuilder();
    sb.append(defaultUserAgent);
    sb.append(" SmarterSecureBrowser/1.0");
    sb.append(" OS/");
    sb.append(mDeviceStatus.operatingSystem);
    sb.append(" Version/");
    sb.append(mDeviceStatus.operatingSystemVersion);
    sb.append(" Model/");
    sb.append(mDeviceStatus.model);

    settings.setUserAgentString(sb.toString());
}

From source file:com.slarker.tech.hi0734.view.widget.webview.AdvancedWebView.java

public void setDesktopMode(final boolean enabled) {
    final WebSettings webSettings = getSettings();

    final String newUserAgent;
    if (enabled) {
        newUserAgent = webSettings.getUserAgentString().replace("Mobile", "eliboM").replace("Android",
                "diordnA");
    } else {//from w  ww  .j  av  a  2  s .c om
        newUserAgent = webSettings.getUserAgentString().replace("eliboM", "Mobile").replace("diordnA",
                "Android");
    }
    webSettings.setUserAgentString(newUserAgent);
    webSettings.setUseWideViewPort(enabled);
    webSettings.setLoadWithOverviewMode(enabled);
    webSettings.setSupportZoom(enabled);
    webSettings.setBuiltInZoomControls(enabled);
}

From source file:com.codename1.impl.android.AndroidImplementation.java

private String getUserAgent() {
    try {// ww  w  .j  a  v a2s .c  om
        String userAgent = System.getProperty("http.agent");
        if (userAgent != null) {
            return userAgent;
        }
    } catch (Exception e) {
    }
    if (getActivity() == null) {
        return "Android-CN1";
    }
    try {
        Constructor<WebSettings> constructor = WebSettings.class.getDeclaredConstructor(Context.class,
                WebView.class);
        constructor.setAccessible(true);
        try {
            WebSettings settings = constructor.newInstance(getActivity(), null);
            return settings.getUserAgentString();
        } finally {
            constructor.setAccessible(false);
        }
    } catch (Exception e) {
        final StringBuffer ua = new StringBuffer();
        if (Thread.currentThread().getName().equalsIgnoreCase("main")) {
            WebView m_webview = new WebView(getActivity());
            ua.append(m_webview.getSettings().getUserAgentString());
            m_webview.destroy();
        } else {
            final boolean[] flag = new boolean[1];
            Thread thread = new Thread() {
                public void run() {
                    Looper.prepare();
                    WebView m_webview = new WebView(getActivity());
                    ua.append(m_webview.getSettings().getUserAgentString());
                    m_webview.destroy();
                    Looper.loop();
                    flag[0] = true;
                    synchronized (flag) {
                        flag.notify();
                    }
                }
            };
            thread.setUncaughtExceptionHandler(AndroidImplementation.exceptionHandler);
            thread.start();
            while (!flag[0]) {
                synchronized (flag) {
                    try {
                        flag.wait(100);
                    } catch (InterruptedException ex) {
                    }
                }
            }
        }
        return ua.toString();
    }
}