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

The following examples show how to use android.webkit.WebSettings#setDomStorageEnabled() . 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: BrowseActivity.java    From AndroidDownload with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.setTopBarTitle("详情页面");
    Intent getIntent = getIntent();
    btUrl=getIntent.getStringExtra("url");
    lt = new LoadToast(this);
    webView.setWebChromeClient(new MyWebChromeClient());
    WebSettings webSettings = webView.getSettings();
    webSettings.setAppCacheEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.supportMultipleWindows();
    webSettings.setAllowContentAccess(true);
    webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
    webSettings.setUseWideViewPort(true);
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setSavePassword(true);
    webSettings.setSaveFormData(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    webSettings.setLoadsImagesAutomatically(true);
    webSettings.setJavaScriptEnabled(false);
    webView.setWebViewClient(new WebViewClient());
    webView.loadUrl(btUrl);
    lt.setTranslationY(200).setBackgroundColor(getResources().getColor(R.color.colorMain)).setProgressColor(getResources().getColor(R.color.white));
    lt.show();
}
 
Example 2
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 3
Source File: PreviewFragment.java    From timecat with Apache License 2.0 6 votes vote down vote up
public void configWebView() {
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);

    webView.setVerticalScrollBarEnabled(false);
    webView.setHorizontalScrollBarEnabled(false);
    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                pageFinish = true;
            }
        }
    });
    webView.loadUrl("file:///android_asset/markdown.html");
}
 
Example 4
Source File: TDialog.java    From letv with Apache License 2.0 5 votes vote down vote up
@SuppressLint({"SetJavaScriptEnabled"})
private void b() {
    this.i.setVerticalScrollBarEnabled(false);
    this.i.setHorizontalScrollBarEnabled(false);
    this.i.setWebViewClient(new FbWebViewClient());
    this.i.setWebChromeClient(this.mChromeClient);
    this.i.clearFormData();
    WebSettings settings = this.i.getSettings();
    settings.setSavePassword(false);
    settings.setSaveFormData(false);
    settings.setCacheMode(-1);
    settings.setNeedInitialFocus(false);
    settings.setBuiltInZoomControls(true);
    settings.setSupportZoom(true);
    settings.setRenderPriority(RenderPriority.HIGH);
    settings.setJavaScriptEnabled(true);
    if (!(this.c == null || this.c.get() == null)) {
        settings.setDatabaseEnabled(true);
        settings.setDatabasePath(((Context) this.c.get()).getApplicationContext().getDir("databases", 0).getPath());
    }
    settings.setDomStorageEnabled(true);
    this.jsBridge.a(new JsListener(), "sdk_js_if");
    this.i.loadUrl(this.e);
    this.i.setLayoutParams(a);
    this.i.setVisibility(4);
    this.i.getSettings().setSavePassword(false);
}
 
Example 5
Source File: WebViewActivity.java    From movienow with GNU General Public License v3.0 5 votes vote down vote up
private void initWebSettings() {
    WebSettings webSettings = webViewT.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setBuiltInZoomControls(true);
    webSettings.setSupportZoom(true);
    webSettings.setDisplayZoomControls(false);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    webSettings.setAllowFileAccess(true);
    webSettings.setDefaultTextEncodingName("UTF-8");
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setUseWideViewPort(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
    String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
    webSettings.setAppCachePath(appCachePath);
    webSettings.setAllowFileAccess(true);
    webSettings.setAppCacheEnabled(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    }
    webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    int mDensity = metrics.densityDpi;
    if (mDensity == 240) {
        webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
    } else if (mDensity == 160) {
        webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
    } else if (mDensity == 120) {
        webSettings.setDefaultZoom(WebSettings.ZoomDensity.CLOSE);
    } else if (mDensity == DisplayMetrics.DENSITY_XHIGH) {
        webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
    } else if (mDensity == DisplayMetrics.DENSITY_TV) {
        webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
    } else {
        webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
    }
}
 
Example 6
Source File: ShopDetailFragment.java    From YCShopDetailLayout with Apache License 2.0 5 votes vote down vote up
@SuppressLint("ObsoleteSdkInt")
private void initWebView() {
    final WebSettings settings = webView.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setSupportZoom(true);
    settings.setBuiltInZoomControls(true);
    settings.setUseWideViewPort(true);
    settings.setDomStorageEnabled(true);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
        new Object() {
            void setLoadWithOverviewMode(boolean overview) {
                settings.setLoadWithOverviewMode(overview);
            }
        }.setLoadWithOverviewMode(true);
    }

    settings.setCacheMode(WebSettings.LOAD_DEFAULT);

    webView.loadUrl("https://www.jianshu.com/p/d745ea0cb5bd");
}
 
Example 7
Source File: MainActivity.java    From webTube with GNU General Public License v3.0 5 votes vote down vote up
public void setUpWebview() {
    // To save login info
    CookieHelper.acceptCookies(webView, true);

    // Some settings
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(false);
    webSettings.setAllowFileAccess(false);

    webSettings.setDatabaseEnabled(true);

    String cachePath = mApplicationContext
            .getDir("cache", Context.MODE_PRIVATE).getPath();
    webSettings.setAppCachePath(cachePath);
    webSettings.setAllowFileAccess(true);
    webSettings.setAppCacheEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);

    webView.setHorizontalScrollBarEnabled(false);

    webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

    webView.setBackgroundColor(Color.WHITE);
    webView.setScrollbarFadingEnabled(true);
    webView.setNetworkAvailable(true);
}
 
Example 8
Source File: MainActivity.java    From chromium-webview-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Convenience method to set some generic defaults for a
 * given WebView
 *
 * @param webView
 */
@TargetApi(Build.VERSION_CODES.L)
private void setUpWebViewDefaults(WebView webView) {
    WebSettings settings = webView.getSettings();

    // Enable Javascript
    settings.setJavaScriptEnabled(true);

    // Use WideViewport and Zoom out if there is no viewport defined
    settings.setUseWideViewPort(true);
    settings.setLoadWithOverviewMode(true);

    // Enable pinch to zoom without the zoom buttons
    settings.setBuiltInZoomControls(true);

    // Allow use of Local Storage
    settings.setDomStorageEnabled(true);

    if(Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
        // Hide the zoom controls for HONEYCOMB+
        settings.setDisplayZoomControls(false);
    }

    // Enable remote debugging via chrome://inspect
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }

    webView.setWebViewClient(new WebViewClient());

    // AppRTC requires third party cookies to work
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptThirdPartyCookies(mWebRTCWebView, true);
}
 
Example 9
Source File: Html5WebView.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
@SuppressLint("SetJavaScriptEnabled")
private void initWebSettings() {
    WebSettings settings = getSettings();
    settings.setJavaScriptEnabled(true);
    getSettings().setUseWideViewPort(true);
    settings.setCacheMode(WebSettings.LOAD_DEFAULT);
    settings.setDomStorageEnabled(true);
    settings.setAppCacheEnabled(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    }
}
 
Example 10
Source File: TDialog.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
private void d()
{
    j.setVerticalScrollBarEnabled(false);
    j.setHorizontalScrollBarEnabled(false);
    j.setWebViewClient(new m(this, null));
    j.setWebChromeClient(mChromeClient);
    j.clearFormData();
    WebSettings websettings = j.getSettings();
    websettings.setSavePassword(false);
    websettings.setSaveFormData(false);
    websettings.setCacheMode(-1);
    websettings.setNeedInitialFocus(false);
    websettings.setBuiltInZoomControls(true);
    websettings.setSupportZoom(true);
    websettings.setRenderPriority(android.webkit.WebSettings.RenderPriority.HIGH);
    websettings.setJavaScriptEnabled(true);
    if (c != null && c.get() != null)
    {
        websettings.setDatabaseEnabled(true);
        websettings.setDatabasePath(((Context)c.get()).getApplicationContext().getDir("databases", 0).getPath());
    }
    websettings.setDomStorageEnabled(true);
    jsBridge.a(new n(this, null), "sdk_js_if");
    j.loadUrl(f);
    j.setLayoutParams(a);
    j.setVisibility(4);
    j.getSettings().setSavePassword(false);
}
 
Example 11
Source File: FullScreenView.java    From letv with Apache License 2.0 5 votes vote down vote up
public void initModule(Context context, c cVar) {
    m mVar = (m) cVar;
    CharSequence charSequence = mVar.E;
    setFocusable(true);
    this.mWebView = (WebView) findViewById(getResources().getIdentifier(z[3], z[2], context.getPackageName()));
    this.rlTitleBar = (RelativeLayout) findViewById(getResources().getIdentifier(z[5], z[2], context.getPackageName()));
    this.tvTitle = (TextView) findViewById(getResources().getIdentifier(z[8], z[2], context.getPackageName()));
    this.imgBtnBack = (ImageButton) findViewById(getResources().getIdentifier(z[1], z[2], context.getPackageName()));
    if (this.mWebView == null || this.rlTitleBar == null || this.tvTitle == null || this.imgBtnBack == null) {
        z.e(TAG, z[7]);
        ((Activity) this.mContext).finish();
    }
    if (1 == mVar.G) {
        this.rlTitleBar.setVisibility(8);
        ((Activity) context).getWindow().setFlags(1024, 1024);
    } else {
        this.tvTitle.setText(charSequence);
        this.imgBtnBack.setOnClickListener(this.btnBackClickListener);
    }
    this.mWebView.setScrollbarFadingEnabled(true);
    this.mWebView.setScrollBarStyle(33554432);
    WebSettings settings = this.mWebView.getSettings();
    settings.setDomStorageEnabled(true);
    a.a(settings);
    webViewHelper = new f(context, cVar);
    this.mWebView.removeJavascriptInterface(z[6]);
    this.mWebView.setWebChromeClient(new cn.jpush.android.b.a.a(z[4], b.class));
    this.mWebView.setWebViewClient(new c(cVar));
    b.setWebViewHelper(webViewHelper);
}
 
Example 12
Source File: BrowserActivity.java    From ProjectX with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setSupportActionBar(R.id.browser_toolbar);
    final String url = getIntent().getStringExtra(EXTRA_URL);
    if (TextUtils.isEmpty(url)) {
        finish();
        return;
    }
    setTitle("");
    mVContent = findViewById(R.id.browser_wb_content);
    WebSettings webSettings = mVContent.getSettings();
    webSettings.setUseWideViewPort(true);
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setSupportZoom(true);
    webSettings.setNeedInitialFocus(true);
    webSettings.setBuiltInZoomControls(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    webSettings.setBlockNetworkImage(false);
    webSettings.setLoadsImagesAutomatically(true);
    webSettings.setDisplayZoomControls(false);
    webSettings.setDomStorageEnabled(true);
    webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
    if (Build.VERSION.SDK_INT >= 21) {
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    }
    webSettings.setDefaultTextEncodingName("utf-8");
    mVContent.setWebViewClient(new PowerfulWebView.StateWebViewClient());
    mVContent.setOnTitleListener(this);
    mVContent.loadUrl(url);
}
 
Example 13
Source File: PKDialog.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
private void d()
{
    n.setVerticalScrollBarEnabled(false);
    n.setHorizontalScrollBarEnabled(false);
    n.setWebViewClient(new e(this, null));
    n.setWebChromeClient(mChromeClient);
    n.clearFormData();
    WebSettings websettings = n.getSettings();
    websettings.setSavePassword(false);
    websettings.setSaveFormData(false);
    websettings.setCacheMode(-1);
    websettings.setNeedInitialFocus(false);
    websettings.setBuiltInZoomControls(true);
    websettings.setSupportZoom(true);
    websettings.setRenderPriority(android.webkit.WebSettings.RenderPriority.HIGH);
    websettings.setJavaScriptEnabled(true);
    if (o != null && o.get() != null)
    {
        websettings.setDatabaseEnabled(true);
        websettings.setDatabasePath(((Context)o.get()).getApplicationContext().getDir("databases", 0).getPath());
    }
    websettings.setDomStorageEnabled(true);
    jsBridge.a(new f(this, null), "sdk_js_if");
    n.clearView();
    n.loadUrl(i);
    n.getSettings().setSavePassword(false);
}
 
Example 14
Source File: FeedBackActivity.java    From shinny-futures-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void initData() {
    mBinding = (ActivityFeedBackBinding) mViewDataBinding;
    WebSettings settings = mBinding.webView.getSettings();
    settings.setDomStorageEnabled(true);
    settings.setJavaScriptEnabled(true);  //设置WebView属性,运行执行js脚本
    settings.setUseWideViewPort(true);//将图片调整到适合webView的大小
    settings.setLoadWithOverviewMode(true);   //自适应屏幕
    settings.setBuiltInZoomControls(true);
    settings.setDisplayZoomControls(false);
    settings.setSupportZoom(true);//设定支持缩放
    settings.setDefaultTextEncodingName("utf-8");
    settings.setLoadsImagesAutomatically(true);
    mBinding.webView.loadUrl(CommonConstants.FEED_BACK_URL);//调用loadUrl方法为WebView加入链接
}
 
Example 15
Source File: SplashActivity.java    From appinventor-extensions with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  JavaInterface android = new JavaInterface(this);
  handler = new Handler();
  webview = new WebView(this);
  WebSettings webSettings = webview.getSettings();
  webSettings.setJavaScriptEnabled(true);
  webSettings.setDatabaseEnabled(true);
  webSettings.setDomStorageEnabled(true);
  String databasePath = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
  webSettings.setDatabasePath(databasePath);

  // webview.setWebViewClient(new WebViewClient() {
  //     @Override
  //     public boolean shouldOverrideUrlLoading(WebView view, String url) {
  //       Log.i("WebView", "Handling url " + url);
  //       Uri uri = Uri.parse(url);
  //       String scheme = uri.getScheme();
  //       if (scheme.equals(Form.APPINVENTOR_URL_SCHEME)) {
  //         Intent resultIntent = new Intent();
  //         resultIntent.setData(uri);
  //         setResult(RESULT_OK, resultIntent);
  //         finish();
  //       } else {
  //         view.loadUrl(url);
  //       }
  //       return true;
  //     }
  //   });

  webview.setWebChromeClient(new WebChromeClient() {
      @Override
      public void onExceededDatabaseQuota(String url, String databaseIdentifier,
        long currentQuota, long estimatedSize, long totalUsedQuota,
        WebStorage.QuotaUpdater quotaUpdater) {
        quotaUpdater.updateQuota(5 * 1024 * 1024);
      }
    });
  setContentView(webview);
  // Uncomment the line below to enable debugging
  // the splash screen (splash.html)
  //
  // webview.setWebContentsDebuggingEnabled(true);
  webview.addJavascriptInterface(android, "Android");
  webview.loadUrl("file:///android_asset/splash.html");
}
 
Example 16
Source File: BaseWebFragment.java    From Android-Application-ZJB with Apache License 2.0 4 votes vote down vote up
protected void initialize() {
    //添加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)));
}
 
Example 17
Source File: ClassicWebViewProvider.java    From focus-android with Mozilla Public License 2.0 4 votes vote down vote up
@SuppressLint("SetJavaScriptEnabled") // We explicitly want to enable JavaScript
private void configureDefaultSettings(Context context, WebSettings settings) {
    settings.setJavaScriptEnabled(true);

    // Needs to be enabled to display some HTML5 sites that use local storage
    settings.setDomStorageEnabled(true);

    // Enabling built in zooming shows the controls by default
    settings.setBuiltInZoomControls(true);

    // So we hide the controls after enabling zooming
    settings.setDisplayZoomControls(false);

    // To respect the html viewport:
    settings.setLoadWithOverviewMode(true);

    // Also increase text size to fill the viewport (this mirrors the behaviour of Firefox,
    // Chrome does this in the current Chrome Dev, but not Chrome release).
    settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);

    // Disable access to arbitrary local files by webpages - assets can still be loaded
    // via file:///android_asset/res, so at least error page images won't be blocked.
    settings.setAllowFileAccess(false);
    settings.setAllowFileAccessFromFileURLs(false);
    settings.setAllowUniversalAccessFromFileURLs(false);

    final String appName = context.getResources().getString(R.string.useragent_appname);
    settings.setUserAgentString(buildUserAgentString(context, settings, appName));

    // Right now I do not know why we should allow loading content from a content provider
    settings.setAllowContentAccess(false);

    // The default for those settings should be "false" - But we want to be explicit.
    settings.setAppCacheEnabled(false);
    settings.setDatabaseEnabled(false);
    settings.setJavaScriptCanOpenWindowsAutomatically(false);

    // We do not implement the callbacks - So let's disable it.
    settings.setGeolocationEnabled(false);

    // We do not want to save any data...
    settings.setSaveFormData(false);
    //noinspection deprecation - This method is deprecated but let's call it in case WebView implementations still obey it.
    settings.setSavePassword(false);
}
 
Example 18
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 19
Source File: EditAreaView.java    From 920-text-editor-v2 with Apache License 2.0 4 votes vote down vote up
public EditAreaView(Context context, AttributeSet attrs) {
        super(context, attrs);

        if (L.debug) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                setWebContentsDebuggingEnabled(true);
            }
        }

        setLongClickable(false);
        setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });

        WebSettings ws = getSettings();
        ws.setDefaultZoom(WebSettings.ZoomDensity.FAR);
        ws.setAllowContentAccess(true);
        ws.setAllowFileAccess(true);
        ws.setBuiltInZoomControls(false);
        ws.setDefaultTextEncodingName("utf-8");
        ws.setDisplayZoomControls(false);
        ws.setSupportZoom(false);
        ws.setLoadWithOverviewMode(false);

        ws.setJavaScriptEnabled(true);
        ws.setAppCacheEnabled(false);
        ws.setDomStorageEnabled(true);
        ws.setAppCacheMaxSize(1024*1024*80);
        ws.setAppCachePath(context.getCacheDir().getPath());
//        ws.setAllowFileAccess(true);
        ws.setCacheMode(WebSettings.LOAD_DEFAULT);

        addJavascriptInterface(new JavascriptApi(), "AndroidEditor");

        setWebViewClient(new EditorViewClient());
        setWebChromeClient(new EditorViewChromeClient());

        pref = Pref.getInstance(getContext());
        ThemeList.Theme theme = pref.getThemeInfo();
        boolean isDark = false;
        if (theme != null) {
            isDark = theme.isDark;
        }

        String html = null;

        try {
            InputStream is = getContext().getAssets().open("editor.html");
            html = IOUtils.readFile(is, "utf-8");
            is.close();
        } catch (Exception e) {
            L.e(e);
            UIUtils.toast(getContext(), R.string.editor_create_unknown_exception);
            return;
        }

        if (!isDark)
            html = html.replaceAll("<\\!\\-\\-\\{DARK\\-START\\}\\-\\->[\\w\\W]+?<\\!\\-\\-\\{DARK\\-END\\}\\-\\->", "");

        loadDataWithBaseURL("file:///android_asset/", html, "text/html", "utf-8", "file:///android_asset/");
        //fix dark theme background spark
        setBackgroundColor(Color.TRANSPARENT);

        pref.registerOnSharedPreferenceChangeListener(this);
        onSharedPreferenceChanged(null, Pref.KEY_FONT_SIZE);
        onSharedPreferenceChanged(null, Pref.KEY_CURSOR_WIDTH);
        onSharedPreferenceChanged(null, Pref.KEY_SHOW_LINE_NUMBER);
        onSharedPreferenceChanged(null, Pref.KEY_WORD_WRAP);
        onSharedPreferenceChanged(null, Pref.KEY_SHOW_WHITESPACE);
        onSharedPreferenceChanged(null, Pref.KEY_TAB_SIZE);
        onSharedPreferenceChanged(null, Pref.KEY_AUTO_INDENT);
        onSharedPreferenceChanged(null, Pref.KEY_AUTO_CAPITALIZE);
        onSharedPreferenceChanged(null, Pref.KEY_INSERT_SPACE_FOR_TAB);
        onSharedPreferenceChanged(null, Pref.KEY_THEME);
        onSharedPreferenceChanged(null, Pref.KEY_TOUCH_TO_ADJUST_TEXT_SIZE);
        enableHighlight(pref.isHighlight());
        setReadOnly(pref.isReadOnly());
    }
 
Example 20
Source File: MainActivity.java    From 2048-android with MIT License 4 votes vote down vote up
@SuppressLint({"SetJavaScriptEnabled", "ShowToast", "ClickableViewAccessibility"})
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Don't show an action bar or title
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    // Enable hardware acceleration
    getWindow().setFlags(LayoutParams.FLAG_HARDWARE_ACCELERATED,
            LayoutParams.FLAG_HARDWARE_ACCELERATED);

    // Apply previous setting about showing status bar or not
    applyFullScreen(isFullScreen());

    // Check if screen rotation is locked in settings
    boolean isOrientationEnabled = false;
    try {
        isOrientationEnabled = Settings.System.getInt(getContentResolver(),
                Settings.System.ACCELEROMETER_ROTATION) == 1;
    } catch (SettingNotFoundException e) {
        Log.d(MAIN_ACTIVITY_TAG, "Settings could not be loaded");
    }

    // If rotation isn't locked and it's a LARGE screen then add orientation changes based on sensor
    int screenLayout = getResources().getConfiguration().screenLayout
            & Configuration.SCREENLAYOUT_SIZE_MASK;
    if (((screenLayout == Configuration.SCREENLAYOUT_SIZE_LARGE)
            || (screenLayout == Configuration.SCREENLAYOUT_SIZE_XLARGE))
            && isOrientationEnabled) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
    }

    setContentView(R.layout.activity_main);

    DialogChangeLog changeLog = DialogChangeLog.newInstance(this);
    if (changeLog.isFirstRun()) {
        changeLog.getLogDialog().show();
    }

    // Load webview with game
    mWebView = findViewById(R.id.mainWebView);
    WebSettings settings = mWebView.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setDomStorageEnabled(true);
    settings.setDatabaseEnabled(true);
    settings.setRenderPriority(RenderPriority.HIGH);
    settings.setDatabasePath(getFilesDir().getParentFile().getPath() + "/databases");

    // If there is a previous instance restore it in the webview
    if (savedInstanceState != null) {
        mWebView.restoreState(savedInstanceState);
    } else {
        // Load webview with current Locale language
        mWebView.loadUrl("file:///android_asset/2048/index.html?lang=" + Locale.getDefault().getLanguage());
    }

    Toast.makeText(getApplication(), R.string.toggle_fullscreen, Toast.LENGTH_SHORT).show();
    // Set fullscreen toggle on webview LongClick
    mWebView.setOnTouchListener((v, event) -> {
        // Implement a long touch action by comparing
        // time between action up and action down
        long currentTime = System.currentTimeMillis();
        if ((event.getAction() == MotionEvent.ACTION_UP)
                && (Math.abs(currentTime - mLastTouch) > mTouchThreshold)) {
            boolean toggledFullScreen = !isFullScreen();
            saveFullScreen(toggledFullScreen);
            applyFullScreen(toggledFullScreen);
        } else if (event.getAction() == MotionEvent.ACTION_DOWN) {
            mLastTouch = currentTime;
        }
        // return so that the event isn't consumed but used
        // by the webview as well
        return false;
    });

    pressBackToast = Toast.makeText(getApplicationContext(), R.string.press_back_again_to_exit,
            Toast.LENGTH_SHORT);
}