Java Code Examples for android.webkit.WebSettings#setUserAgentString()

The following examples show how to use android.webkit.WebSettings#setUserAgentString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebViewFragment.java    From AndroidHttpCapture with MIT License 6 votes vote down vote up
public void setUserAgent(){
    String originUA = userAgentString;

    switch (SharedPreferenceUtils.getString(getContext(),"select_ua", "0")) {
        case "0":
            userAgentString = baseUserAgentString;
            break;
        case "1":
            userAgentString = baseUserAgentString + " MQQBrowser/6.2 TBS/036524 MicroMessenger/6.3.18.800 NetType/WIFI Language/zh_CN";
            break;
        case "2":
            userAgentString = baseUserAgentString + " MQQBrowser/6.2 TBS/036524 V1_AND_SQ_6.0.0_300_YYB_D QQ/6.0.0.2605 NetType/WIFI WebP/0.3.0 Pixel/1440";
            break;
    }
    WebSettings webSettings = webView.getSettings();
    webSettings.setUserAgentString(userAgentString);

    if(!originUA.equals(userAgentString) && webView!=null){
        reload();
    }
}
 
Example 2
Source File: TestCaseListActivity.java    From Android-Plugin-Framework with MIT License 6 votes vote down vote up
private void setUpWebViewSetting(WebView web) {
    WebSettings webSettings = web.getSettings();

    webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);// 根据cache-control决定是否从网络上取数据
    webSettings.setSupportZoom(true);
    webSettings.setBuiltInZoomControls(true);// 显示放大缩小
    webSettings.setJavaScriptEnabled(true);
    // webSettings.setPluginsEnabled(true);
    webSettings.setPluginState(WebSettings.PluginState.ON);
    webSettings.setUserAgentString(webSettings.getUserAgentString());
    webSettings.setDomStorageEnabled(true);
    webSettings.setAppCacheEnabled(true);
    webSettings.setAppCachePath(getCacheDir().getPath());
    webSettings.setUseWideViewPort(true);// 影响默认满屏和双击缩放
    webSettings.setLoadWithOverviewMode(true);// 影响默认满屏和手势缩放

}
 
Example 3
Source File: MyAdvancedWebView.java    From SlimSocial-for-Facebook with GNU General Public License v2.0 6 votes vote down vote up
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 {
        newUserAgent = webSettings.getUserAgentString()
                .replace("eliboM", "Mobile")
                .replace("diordnA", "Android");
    }

    webSettings.setUserAgentString(newUserAgent);
    webSettings.setUseWideViewPort(enabled);
    webSettings.setLoadWithOverviewMode(enabled);
    webSettings.setSupportZoom(enabled);
    webSettings.setBuiltInZoomControls(enabled);
}
 
Example 4
Source File: FunctionUtils.java    From NGA-CLIENT-VER-OPEN-SOURCE with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("static-access")
public static void handleContentTV(final WebView contentTV, final MessageArticlePageInfo row, int bgColor, int fgColor, Context context) {
    final WebViewClient client = new WebViewClientEx((FragmentActivity) context);
    contentTV.setBackgroundColor(0);
    contentTV.setFocusableInTouchMode(false);
    contentTV.setFocusable(false);
    contentTV.setLongClickable(false);


    WebSettings setting = contentTV.getSettings();
    setting.setUserAgentString(context.getString(R.string.clientua) + BuildConfig.VERSION_CODE);
    setting.setDefaultFontSize(PhoneConfiguration.getInstance()
            .getWebSize());
    setting.setJavaScriptEnabled(false);
    contentTV.setWebViewClient(client);

    contentTV.setTag(row.getLou());
    contentTV.loadDataWithBaseURL(null, row.getFormated_html_data(),
            "text/html", "utf-8", null);
}
 
Example 5
Source File: EdxWebView.java    From edx-app-android with Apache License 2.0 6 votes vote down vote up
@SuppressLint("SetJavaScriptEnabled")
public EdxWebView(Context context, AttributeSet attrs) {
    super(context, attrs);
    final WebSettings settings = getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setLoadWithOverviewMode(true);
    settings.setBuiltInZoomControls(false);
    settings.setSupportZoom(true);
    settings.setLoadsImagesAutomatically(true);
    settings.setDomStorageEnabled(true);
    settings.setUserAgentString(
            settings.getUserAgentString() + " " +
                    context.getString(R.string.app_name) + "/" +
                    BuildConfig.APPLICATION_ID + "/" +
                    BuildConfig.VERSION_NAME
    );
    setLayerType(LAYER_TYPE_HARDWARE, null);
}
 
Example 6
Source File: Web3View.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
@SuppressLint("SetJavaScriptEnabled")
public void init() {
    jsInjectorClient = new JsInjectorClient(getContext());
    webViewClient = new Web3ViewClient(jsInjectorClient, new UrlHandlerManager());
    WebSettings webSettings = getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    webSettings.setBuiltInZoomControls(true);
    webSettings.setDisplayZoomControls(false);
    webSettings.setUseWideViewPort(true);
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    webSettings.setUserAgentString(webSettings.getUserAgentString()
                                           + "AlphaWallet(Platform=Android&AppVersion=" + BuildConfig.VERSION_NAME + ")");
    WebView.setWebContentsDebuggingEnabled(true); //so devs can debug their scripts/pages
    addJavascriptInterface(new SignCallbackJSInterface(
            this,
            innerOnSignTransactionListener,
            innerOnSignMessageListener,
            innerOnSignPersonalMessageListener,
            innerOnSignTypedMessageListener), "alpha");
}
 
Example 7
Source File: WebActivity.java    From Android-Plugin-Framework with MIT License 6 votes vote down vote up
private void setUpWebViewSetting() {
	WebSettings webSettings = web.getSettings();

	webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);// 根据cache-control决定是否从网络上取数据
	webSettings.setSupportZoom(true);
	webSettings.setBuiltInZoomControls(true);// 显示放大缩小
	webSettings.setJavaScriptEnabled(true);
	// webSettings.setPluginsEnabled(true);
	webSettings.setPluginState(WebSettings.PluginState.ON);
	webSettings.setUserAgentString(webSettings.getUserAgentString());
	webSettings.setDomStorageEnabled(true);
	webSettings.setAppCacheEnabled(true);
	webSettings.setAppCachePath(getCacheDir().getPath());
	webSettings.setUseWideViewPort(true);// 影响默认满屏和双击缩放
	webSettings.setLoadWithOverviewMode(true);// 影响默认满屏和手势缩放

}
 
Example 8
Source File: KCWebView.java    From kerkee_android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param webSettings
 * **/
private static void setCustomizedUA(WebSettings webSettings)
{

    StringBuilder customizedUA = new StringBuilder(webSettings.getUserAgentString()).append("; ");

    webSettings.setUserAgentString(customizedUA.toString());
}
 
Example 9
Source File: WebViewActivity.java    From Aria2App with GNU General Public License v3.0 5 votes vote down vote up
private void toggleDesktopMode(boolean enabled) {
    WebSettings settings = web.getSettings();

    settings.setLoadWithOverviewMode(enabled);
    settings.setUseWideViewPort(enabled);

    settings.setSupportZoom(enabled);
    settings.setBuiltInZoomControls(enabled);
    settings.setDisplayZoomControls(!enabled);

    String userAgent = enabled ? "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/20100101 Firefox/4.0" : WebSettings.getDefaultUserAgent(this);
    userAgent += " Aria2App/" + BuildConfig.VERSION_NAME + "-" + BuildConfig.FLAVOR;
    settings.setUserAgentString(userAgent);
}
 
Example 10
Source File: AdvanceWebClient.java    From cloudflare-scrape-Android with MIT License 5 votes vote down vote up
public void initWebView(String url) {
    if (mListener == null) {
        throw new RuntimeException("must set listener");
    }
    if (mContext.get() == null) {
        throw new RuntimeException("mContext not find");
    }
    mUrl = url;
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setUseWideViewPort(true);
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setUserAgentString(ua);
    webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
    webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);  //设置 缓存模式
    // 开启 DOM storage API 功能
    webSettings.setDomStorageEnabled(true);
    //开启 database storage API 功能
    webSettings.setDatabaseEnabled(true);
    String cacheDirPath = mContext.get().getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
    //      String cacheDirPath = getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;
    Log.e("WebView", "cacheDirPath=" + cacheDirPath);
    //设置数据库缓存路径
    webSettings.setDatabasePath(cacheDirPath);
    //设置  Application Caches 缓存目录
    webSettings.setAppCachePath(cacheDirPath);
    //开启 Application Caches 功能
    webSettings.setAppCacheEnabled(true);
    Log.e("WebView", "H5--->" + url);
    mWebView.setWebViewClient(this);

    mCookieManager = CookieManager.getInstance();
    mCookieManager.removeAllCookies(null);

    mWebView.loadUrl(mUrl);
}
 
Example 11
Source File: RexxarWebViewCore.java    From rexxar-android with MIT License 5 votes vote down vote up
@TargetApi(16)
@SuppressLint("SetJavaScriptEnabled")
protected void setupWebSettings(WebSettings ws) {
    ws.setAppCacheEnabled(true);
    WebViewCompatUtils.enableJavaScriptForWebView(getContext(), ws);
    ws.setJavaScriptEnabled(true);
    ws.setGeolocationEnabled(true);
    ws.setBuiltInZoomControls(true);
    ws.setDisplayZoomControls(false);

    ws.setAllowFileAccess(true);
    if (Utils.hasJellyBean()) {
        ws.setAllowFileAccessFromFileURLs(true);
        ws.setAllowUniversalAccessFromFileURLs(true);
    }

    // enable html cache
    ws.setDomStorageEnabled(true);
    ws.setAppCacheEnabled(true);
    // Set cache size to 8 mb by default. should be more than enough
    ws.setAppCacheMaxSize(1024 * 1024 * 8);
    // This next one is crazy. It's the DEFAULT location for your app's cache
    // But it didn't work for me without this line
    ws.setAppCachePath("/data/data/" + getContext().getPackageName() + "/cache");
    ws.setAllowFileAccess(true);
    ws.setCacheMode(WebSettings.LOAD_DEFAULT);

    String ua = ws.getUserAgentString() + " " + Rexxar.getUserAgent();
    ws.setUserAgentString(ua);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        ws.setUseWideViewPort(true);
    }

    if (Utils.hasLollipop()) {
        ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    }
}
 
Example 12
Source File: WebViewInitializer.java    From FastWaiMai with MIT License 5 votes vote down vote up
/**
 * 初始化传入的webView
 */
@SuppressLint("SetJavaScriptEnabled")
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public WebView initialWebView(WebView webView){
	webView.setHorizontalScrollBarEnabled(false);
	//不能纵向滚动
	webView.setVerticalScrollBarEnabled(false);
	//允许截图
	webView.setDrawingCacheEnabled(true);
	//屏蔽长按事件
	webView.setOnLongClickListener(new View.OnLongClickListener() {
		@Override
		public boolean onLongClick(View v) {
			return true;
		}
	});
	//初始化WebSettings
	final WebSettings settings = webView.getSettings();
	settings.setJavaScriptEnabled(true);
	final String ua = settings.getUserAgentString();
	settings.setUserAgentString(ua + "Latte");
	//隐藏缩放控件
	settings.setBuiltInZoomControls(false);
	settings.setDisplayZoomControls(false);
	//禁止缩放
	settings.setSupportZoom(false);
	//文件权限
	settings.setAllowFileAccess(true);
	settings.setAllowFileAccessFromFileURLs(true);
	settings.setAllowUniversalAccessFromFileURLs(true);
	settings.setAllowContentAccess(true);
	//缓存相关
	settings.setAppCacheEnabled(true);
	settings.setDomStorageEnabled(true);
	settings.setDatabaseEnabled(true);
	settings.setCacheMode(WebSettings.LOAD_DEFAULT);

	return webView;
}
 
Example 13
Source File: QuickWebView.java    From quickhybrid-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 初始化设置
 */
public void settingWebView() {
    WebSettings settings = getSettings();
    String ua = settings.getUserAgentString();
    // 设置浏览器UA,JS端通过UA判断是否属于Quick环境
    settings.setUserAgentString(ua + " QuickHybridJs/" + BuildConfig.VERSION_NAME);
    // 设置支持JS
    settings.setJavaScriptEnabled(true);
    // 设置是否支持meta标签来控制缩放
    settings.setUseWideViewPort(true);
    // 缩放至屏幕的大小
    settings.setLoadWithOverviewMode(true);
    // 设置内置的缩放控件(若SupportZoom为false,该设置项无效)
    settings.setBuiltInZoomControls(true);
    // 设置缓存模式
    // LOAD_DEFAULT 根据HTTP协议header中设置的cache-control属性来执行加载策略
    // LOAD_CACHE_ELSE_NETWORK 只要本地有无论是否过期都从本地获取
    settings.setCacheMode(WebSettings.LOAD_DEFAULT);
    settings.setDomStorageEnabled(true);
    // 设置AppCache 需要H5页面配置manifest文件(官方已不推介使用)
    String appCachePath = getContext().getCacheDir().getAbsolutePath();
    settings.setAppCachePath(appCachePath);
    settings.setAppCacheEnabled(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // 强制开启android webview debug模式使用Chrome inspect(https://developers.google.com/web/tools/chrome-devtools/remote-debugging/)
        WebView.setWebContentsDebuggingEnabled(true);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        CookieManager.getInstance().setAcceptThirdPartyCookies(this, true);
    }
}
 
Example 14
Source File: SystemWebViewEngine.java    From keemob with MIT License 4 votes vote down vote up
@SuppressLint({"NewApi", "SetJavaScriptEnabled"})
@SuppressWarnings("deprecation")
private void initWebViewSettings() {
    webView.setInitialScale(0);
    webView.setVerticalScrollBarEnabled(false);
    // Enable JavaScript
    final WebSettings settings = webView.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);
    settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL);

    String manufacturer = android.os.Build.MANUFACTURER;
    LOG.d(TAG, "CordovaWebView is running on device made by: " + manufacturer);

    //We don't save any form data in the application
    settings.setSaveFormData(false);
    settings.setSavePassword(false);

    // Jellybean rightfully tried to lock this down. Too bad they didn't give us a whitelist
    // while we do this
    settings.setAllowUniversalAccessFromFileURLs(true);
    settings.setMediaPlaybackRequiresUserGesture(false);

    // Enable database
    // We keep this disabled because we use or shim to get around DOM_EXCEPTION_ERROR_16
    String databasePath = webView.getContext().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
    settings.setDatabaseEnabled(true);
    settings.setDatabasePath(databasePath);


    //Determine whether we're in debug or release mode, and turn on Debugging!
    ApplicationInfo appInfo = webView.getContext().getApplicationContext().getApplicationInfo();
    if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
        enableRemoteDebugging();
    }

    settings.setGeolocationDatabasePath(databasePath);

    // Enable DOM storage
    settings.setDomStorageEnabled(true);

    // Enable built-in geolocation
    settings.setGeolocationEnabled(true);

    // Enable AppCache
    // Fix for CB-2282
    settings.setAppCacheMaxSize(5 * 1048576);
    settings.setAppCachePath(databasePath);
    settings.setAppCacheEnabled(true);

    // Fix for CB-1405
    // Google issue 4641
    String defaultUserAgent = settings.getUserAgentString();

    // Fix for CB-3360
    String overrideUserAgent = preferences.getString("OverrideUserAgent", null);
    if (overrideUserAgent != null) {
        settings.setUserAgentString(overrideUserAgent);
    } else {
        String appendUserAgent = preferences.getString("AppendUserAgent", null);
        if (appendUserAgent != null) {
            settings.setUserAgentString(defaultUserAgent + " " + appendUserAgent);
        }
    }
    // End CB-3360

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
    if (this.receiver == null) {
        this.receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                settings.getUserAgentString();
            }
        };
        webView.getContext().registerReceiver(this.receiver, intentFilter);
    }
    // end CB-1405
}
 
Example 15
Source File: AuthActivity.java    From letv with Apache License 2.0 4 votes vote down vote up
protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    try {
        Bundle extras = getIntent().getExtras();
        if (extras == null) {
            finish();
            return;
        }
        try {
            this.d = extras.getString(b);
            String string = extras.getString("params");
            if (k.a(string)) {
                Method method;
                super.requestWindowFeature(1);
                this.f = new Handler(getMainLooper());
                View linearLayout = new LinearLayout(getApplicationContext());
                LayoutParams layoutParams = new LinearLayout.LayoutParams(-1, -1);
                linearLayout.setOrientation(1);
                setContentView(linearLayout, layoutParams);
                this.c = new WebView(getApplicationContext());
                layoutParams.weight = 1.0f;
                this.c.setVisibility(0);
                linearLayout.addView(this.c, layoutParams);
                WebSettings settings = this.c.getSettings();
                settings.setUserAgentString(settings.getUserAgentString() + k.c(getApplicationContext()));
                settings.setRenderPriority(RenderPriority.HIGH);
                settings.setSupportMultipleWindows(true);
                settings.setJavaScriptEnabled(true);
                settings.setSavePassword(false);
                settings.setJavaScriptCanOpenWindowsAutomatically(true);
                settings.setMinimumFontSize(settings.getMinimumFontSize() + 8);
                settings.setAllowFileAccess(false);
                settings.setTextSize(TextSize.NORMAL);
                this.c.setVerticalScrollbarOverlay(true);
                this.c.setWebViewClient(new b());
                this.c.setWebChromeClient(new a());
                this.c.setDownloadListener(new a(this));
                this.c.loadUrl(string);
                if (VERSION.SDK_INT >= 7) {
                    try {
                        method = this.c.getSettings().getClass().getMethod("setDomStorageEnabled", new Class[]{Boolean.TYPE});
                        if (method != null) {
                            method.invoke(this.c.getSettings(), new Object[]{Boolean.valueOf(true)});
                        }
                    } catch (Exception e) {
                    }
                }
                try {
                    method = this.c.getClass().getMethod("removeJavascriptInterface", new Class[0]);
                    if (method != null) {
                        method.invoke(this.c, new Object[]{"searchBoxJavaBridge_"});
                        return;
                    }
                    return;
                } catch (Exception e2) {
                    return;
                }
            }
            finish();
        } catch (Exception e3) {
            finish();
        }
    } catch (Exception e4) {
        finish();
    }
}
 
Example 16
Source File: SystemWebViewEngine.java    From countly-sdk-cordova with MIT License 4 votes vote down vote up
@SuppressLint({"NewApi", "SetJavaScriptEnabled"})
@SuppressWarnings("deprecation")
private void initWebViewSettings() {
    webView.setInitialScale(0);
    webView.setVerticalScrollBarEnabled(false);
    // Enable JavaScript
    final WebSettings settings = webView.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);
    settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL);

    String manufacturer = android.os.Build.MANUFACTURER;
    LOG.d(TAG, "CordovaWebView is running on device made by: " + manufacturer);

    //We don't save any form data in the application
    settings.setSaveFormData(false);
    settings.setSavePassword(false);

    // Jellybean rightfully tried to lock this down. Too bad they didn't give us a whitelist
    // while we do this
    settings.setAllowUniversalAccessFromFileURLs(true);
    settings.setMediaPlaybackRequiresUserGesture(false);

    // Enable database
    // We keep this disabled because we use or shim to get around DOM_EXCEPTION_ERROR_16
    String databasePath = webView.getContext().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
    settings.setDatabaseEnabled(true);
    settings.setDatabasePath(databasePath);


    //Determine whether we're in debug or release mode, and turn on Debugging!
    ApplicationInfo appInfo = webView.getContext().getApplicationContext().getApplicationInfo();
    if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
        enableRemoteDebugging();
    }

    settings.setGeolocationDatabasePath(databasePath);

    // Enable DOM storage
    settings.setDomStorageEnabled(true);

    // Enable built-in geolocation
    settings.setGeolocationEnabled(true);

    // Enable AppCache
    // Fix for CB-2282
    settings.setAppCacheMaxSize(5 * 1048576);
    settings.setAppCachePath(databasePath);
    settings.setAppCacheEnabled(true);

    // Fix for CB-1405
    // Google issue 4641
    String defaultUserAgent = settings.getUserAgentString();

    // Fix for CB-3360
    String overrideUserAgent = preferences.getString("OverrideUserAgent", null);
    if (overrideUserAgent != null) {
        settings.setUserAgentString(overrideUserAgent);
    } else {
        String appendUserAgent = preferences.getString("AppendUserAgent", null);
        if (appendUserAgent != null) {
            settings.setUserAgentString(defaultUserAgent + " " + appendUserAgent);
        }
    }
    // End CB-3360

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
    if (this.receiver == null) {
        this.receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                settings.getUserAgentString();
            }
        };
        webView.getContext().registerReceiver(this.receiver, intentFilter);
    }
    // end CB-1405
}
 
Example 17
Source File: RMBTHelpFragment.java    From open-rmbt with Apache License 2.0 4 votes vote down vote up
/**
* 
*/
  @SuppressLint("SetJavaScriptEnabled")
  @Override
  public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
  {
      
      super.onCreateView(inflater, container, savedInstanceState);
      
      final Bundle args = getArguments();
      
      String url = args.getString(ARG_URL);
      
      if (url == null || url.length() == 0)
          url = this.getString(R.string.url_help);
      
      final Activity activity = getActivity();
      
      final WebView webview = new WebView(activity)
      {
          @Override
          public boolean onKeyDown(final int keyCode, final KeyEvent event)
          {
              if (keyCode == KeyEvent.KEYCODE_BACK && canGoBack())
              {
                  goBack();
                  return true;
              }
              return super.onKeyDown(keyCode, event);
          }
      };
      
      final WebSettings webSettings = webview.getSettings();
      final String userAgent = AppConstants.getUserAgentString(getActivity());
      if (userAgent != null) {
      	webSettings.setUserAgentString(userAgent);
      }
      webSettings.setJavaScriptEnabled(true);
      
      webview.setWebViewClient(new WebViewClient()
      {
          @Override
          public void onReceivedError(final WebView view, final int errorCode, final String description,
                  final String failingUrl)
          {
              Log.w(getTag(), "error code:" + errorCode);
              Log.d(getTag(), "error desc:" + description);
              Log.d(getTag(), "error url:" + failingUrl);
              webview.loadUrl("file:///android_res/raw/error.html");
              super.onReceivedError(view, errorCode, description, failingUrl);
          }
      });
      
      if (! url.matches("^https?://.*"))
      {
          final String protocol = ConfigHelper.isControlSeverSSL(activity) ? "https" : "http";
          url = protocol + "://" + url;
      }
      
      webview.loadUrl(url);
      
      return webview;
  }
 
Example 18
Source File: SystemWebViewEngine.java    From keemob with MIT License 4 votes vote down vote up
@SuppressLint({"NewApi", "SetJavaScriptEnabled"})
@SuppressWarnings("deprecation")
private void initWebViewSettings() {
    webView.setInitialScale(0);
    webView.setVerticalScrollBarEnabled(false);
    // Enable JavaScript
    final WebSettings settings = webView.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);
    settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL);

    String manufacturer = android.os.Build.MANUFACTURER;
    LOG.d(TAG, "CordovaWebView is running on device made by: " + manufacturer);

    //We don't save any form data in the application
    settings.setSaveFormData(false);
    settings.setSavePassword(false);

    // Jellybean rightfully tried to lock this down. Too bad they didn't give us a whitelist
    // while we do this
    settings.setAllowUniversalAccessFromFileURLs(true);
    settings.setMediaPlaybackRequiresUserGesture(false);

    // Enable database
    // We keep this disabled because we use or shim to get around DOM_EXCEPTION_ERROR_16
    String databasePath = webView.getContext().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
    settings.setDatabaseEnabled(true);
    settings.setDatabasePath(databasePath);


    //Determine whether we're in debug or release mode, and turn on Debugging!
    ApplicationInfo appInfo = webView.getContext().getApplicationContext().getApplicationInfo();
    if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
        enableRemoteDebugging();
    }

    settings.setGeolocationDatabasePath(databasePath);

    // Enable DOM storage
    settings.setDomStorageEnabled(true);

    // Enable built-in geolocation
    settings.setGeolocationEnabled(true);

    // Enable AppCache
    // Fix for CB-2282
    settings.setAppCacheMaxSize(5 * 1048576);
    settings.setAppCachePath(databasePath);
    settings.setAppCacheEnabled(true);

    // Fix for CB-1405
    // Google issue 4641
    String defaultUserAgent = settings.getUserAgentString();

    // Fix for CB-3360
    String overrideUserAgent = preferences.getString("OverrideUserAgent", null);
    if (overrideUserAgent != null) {
        settings.setUserAgentString(overrideUserAgent);
    } else {
        String appendUserAgent = preferences.getString("AppendUserAgent", null);
        if (appendUserAgent != null) {
            settings.setUserAgentString(defaultUserAgent + " " + appendUserAgent);
        }
    }
    // End CB-3360

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
    if (this.receiver == null) {
        this.receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                settings.getUserAgentString();
            }
        };
        webView.getContext().registerReceiver(this.receiver, intentFilter);
    }
    // end CB-1405
}
 
Example 19
Source File: H5PayActivity.java    From letv with Apache License 2.0 4 votes vote down vote up
protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    try {
        Bundle extras = getIntent().getExtras();
        if (extras == null) {
            finish();
            return;
        }
        try {
            String string = extras.getString("url");
            if (k.a(string)) {
                Method method;
                super.requestWindowFeature(1);
                this.c = new Handler(getMainLooper());
                Object string2 = extras.getString("cookie");
                if (!TextUtils.isEmpty(string2)) {
                    CookieSyncManager.createInstance(getApplicationContext()).sync();
                    CookieManager.getInstance().setCookie(string, string2);
                    CookieSyncManager.getInstance().sync();
                }
                View linearLayout = new LinearLayout(getApplicationContext());
                LayoutParams layoutParams = new LinearLayout.LayoutParams(-1, -1);
                linearLayout.setOrientation(1);
                setContentView(linearLayout, layoutParams);
                this.a = new WebView(getApplicationContext());
                layoutParams.weight = 1.0f;
                this.a.setVisibility(0);
                linearLayout.addView(this.a, layoutParams);
                WebSettings settings = this.a.getSettings();
                settings.setUserAgentString(settings.getUserAgentString() + k.c(getApplicationContext()));
                settings.setRenderPriority(RenderPriority.HIGH);
                settings.setSupportMultipleWindows(true);
                settings.setJavaScriptEnabled(true);
                settings.setSavePassword(false);
                settings.setJavaScriptCanOpenWindowsAutomatically(true);
                settings.setMinimumFontSize(settings.getMinimumFontSize() + 8);
                settings.setAllowFileAccess(false);
                settings.setTextSize(TextSize.NORMAL);
                this.a.setVerticalScrollbarOverlay(true);
                this.a.setWebViewClient(new a());
                this.a.loadUrl(string);
                if (VERSION.SDK_INT >= 7) {
                    try {
                        method = this.a.getSettings().getClass().getMethod("setDomStorageEnabled", new Class[]{Boolean.TYPE});
                        if (method != null) {
                            method.invoke(this.a.getSettings(), new Object[]{Boolean.valueOf(true)});
                        }
                    } catch (Exception e) {
                    }
                }
                try {
                    method = this.a.getClass().getMethod("removeJavascriptInterface", new Class[0]);
                    if (method != null) {
                        method.invoke(this.a, new Object[]{"searchBoxJavaBridge_"});
                        return;
                    }
                    return;
                } catch (Exception e2) {
                    return;
                }
            }
            finish();
        } catch (Exception e3) {
            finish();
        }
    } catch (Exception e4) {
        finish();
    }
}
 
Example 20
Source File: AbsWebActivity.java    From Android-Application-ZJB with Apache License 2.0 4 votes vote down vote up
protected void initView() {
    //添加H5的基本参数
    UrlParserManager.getInstance().addParams(UrlParserManager.METHOD_CHANNEL, "app");
    mParamBuilder = getParams();
    mUrl = UrlParserManager.getInstance().parsePlaceholderUrl(mParamBuilder.getUrl());

    mWebView.setProgressbar(mProgressBar);
    WebSettings ws = mWebView.getSettings();
    ws.setBuiltInZoomControls(false); // 缩放
    ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
    ws.setUseWideViewPort(true);
    ws.setLoadWithOverviewMode(true);
    ws.setSaveFormData(true);
    ws.setDomStorageEnabled(true);//开启 database storage API 功能
    //设置自定义UserAgent
    String agent = ws.getUserAgentString();
    ws.setUserAgentString(createUserAgent(agent));
    mWebView.setDownloadListener((url, userAgent, contentDisposition, mimeType, contentLength) -> {
        if (url != null && url.startsWith("http://"))
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
    });
    mWebView.loadUrl(mUrl);
    mWebView.setOnKeyListener((v, keyCode, event) -> {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            //表示按返回键时的操作
            if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
                mWebView.goBack();   //后退
                return true;    //已处理
            }
        }
        return false;
    });

    mWebView.setDefaultHandler(new DefaultHandler());
    //注册分享方法
    mWebView.registerHandler("shareJs", (data, function) -> {
        try {
            if (!TextUtils.isEmpty(data)) {
                WebShareBean shareBean = GsonUtil.fromJson(data, WebShareBean.class);
                shareJs(shareBean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    });

    //注册设置标题方法
    mWebView.registerHandler("webTitleJs", ((data, function) -> webTitleJs(data)));
    //注册设置分享按钮方法
    mWebView.registerHandler("disableShareJs", ((data, function) -> {
        if ("true".equals(data)) {
            disableShareJs(true);
        } else {
            disableShareJs(false);
        }

    }));

    //注册微信支付
    mWebView.registerHandler("wxPayJs", ((data, function) -> wxPayJs(data)));
}