android.webkit.WebSettings

Here are the examples of the java api android.webkit.WebSettings taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

467 Examples 7

19 Source : AboutActivity.java
with Apache License 2.0
from zhou-you

/**
 * <p>描述:关于我</p>
 * 作者: zhouyou<br>
 * 日期: 2017/11/1 20:32 <br>
 * 版本: v1.0<br>
 */
public clreplaced AboutActivity extends AppCompatActivity {

    private WebView m_webview;

    private WebSettings webSetting;

    // web缓存目录
    private static final String APP_CACHE_DIRNAME = "/webcache";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_about);
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setreplacedle("关于我");
        }
        m_webview = (WebView) findViewById(R.id.webbrowser);
        initWebView(m_webview);
        m_webview.loadUrl("file:///android_replacedet/about.html");
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.gereplacedemId()) {
            case android.R.id.home:
                // back button
                this.finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressLint("SetJavaScriptEnabled")
    public void initWebView(final WebView webView) {
        if (webView == null) {
            throw new RuntimeException(" WebView object is not null,plase invoke initWebView() !!!!");
        }
        m_webview = webView;
        webSetting = m_webview.getSettings();
        if (Build.VERSION.SDK_INT >= 19) {
            webSetting.setLoadsImagesAutomatically(true);
        } else {
            webSetting.setLoadsImagesAutomatically(false);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // 解决WebView不能加载http与https混合内容的问题
            webSetting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSetting.setJavaScriptEnabled(true);
        webSetting.setDefaultTextEncodingName("utf-8");
        webSetting.setBuiltInZoomControls(true);
        webSetting.setSaveFormData(true);
        webSetting.setBlockNetworkImage(false);
        webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // 应用数据
        webSetting.setAllowFileAccess(true);
        m_webview.setVerticalScrollBarEnabled(false);
        m_webview.setVerticalScrollbarOverlay(false);
        m_webview.setHorizontalScrollBarEnabled(false);
        m_webview.setHorizontalScrollbarOverlay(false);
        webSetting.setSupportZoom(false);
        webSetting.setPluginState(WebSettings.PluginState.ON);
        webSetting.setLoadWithOverviewMode(true);
        // 设置WebView使用广泛的视窗
        webSetting.setUseWideViewPort(true);
        // 设置WebView的用户代理字符串。如果字符串“ua”是null或空,它将使用系统默认的用户代理字符串
        // 注:这里设置后部分手机会加载不出外链的页面
        // webSetting.setUserAgentString(getString(R.string.app_name));
        // 支持手势缩放
        webSetting.setBuiltInZoomControls(true);
        // 自动打开窗口
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        // 排版适应屏幕
        // 设置布局方式 setLightTouchEnabled 设置用鼠标激活被选项
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        // 建议缓存策略为,判断是否有网络,有的话,使用LOAD_DEFAULT,无网络时,使用LOAD_CACHE_ELSE_NETWORK
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        // 开启DOM storage API 功能
        webView.getSettings().setDomStorageEnabled(true);
        // 开启database storage API功能
        webView.getSettings().setDatabaseEnabled(true);
        String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACHE_DIRNAME;
        // Log.i("cachePath", cacheDirPath);
        // 设置数据库缓存路径
        // API 19 deprecated
        webView.getSettings().setDatabasePath(cacheDirPath);
        // 设置Application caches缓存目录
        webView.getSettings().setAppCachePath(cacheDirPath);
        // 开启Application Cache功能
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
    // Log.i("databasepath", webView.getSettings().getDatabasePath());
    // 其他
    // setAllowFileAccess 启用或禁止WebView访问文件数据 setBlockNetworkImage 是否显示网络图像
    // setBuiltInZoomControls 设置是否支持缩放 setCacheMode 设置缓冲的模式
    // setDefaultFontSize 设置默认的字体大小 setDefaultTextEncodingName 设置在解码时使用的默认编码
    // setFixedFontFamily 设置固定使用的字体 setJavaSciptEnabled 设置是否支持Javascript
    // setLayoutAlgorithm 设置布局方式 setLightTouchEnabled 设置用鼠标激活被选项
    // setSupportZoom 设置是否支持变焦
    }
}

19 Source : WebViewHelper.java
with GNU General Public License v3.0
from xtools-at

public clreplaced WebViewHelper {

    // Instance variables
    private Activity activity;

    private UIManager uiManager;

    private WebView webView;

    private WebSettings webSettings;

    public WebViewHelper(Activity activity, UIManager uiManager) {
        this.activity = activity;
        this.uiManager = uiManager;
        this.webView = (WebView) activity.findViewById(R.id.webView);
        this.webSettings = webView.getSettings();
    }

    /**
     * Simple helper method checking if connected to Network.
     * Doesn't check for actual Internet connection!
     * @return {boolean} True if connected to Network.
     */
    private boolean isNetworkAvailable() {
        ConnectivityManager manager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        boolean isAvailable = false;
        if (networkInfo != null && networkInfo.isConnected()) {
            // Wifi or Mobile Network is present and connected
            isAvailable = true;
        }
        return isAvailable;
    }

    // manipulate cache settings to make sure our PWA gets updated
    private void useCache(Boolean use) {
        if (use) {
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        } else {
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        }
    }

    // public method changing cache settings according to network availability.
    // retrieve content from cache primarily if not connected,
    // allow fetching from web too otherwise to get updates.
    public void forceCacheIfOffline() {
        useCache(!isNetworkAvailable());
    }

    // handles initial setup of webview
    public void setupWebView() {
        // accept cookies
        CookieManager.getInstance().setAcceptCookie(true);
        // enable JS
        webSettings.setJavaScriptEnabled(true);
        // must be set for our js-popup-blocker:
        webSettings.setSupportMultipleWindows(true);
        // PWA settings
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            webSettings.setDatabasePath(activity.getApplicationContext().getFilesDir().getAbsolutePath());
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            webSettings.setAppCacheMaxSize(Long.MAX_VALUE);
        }
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCachePath(activity.getApplicationContext().getCacheDir().getAbsolutePath());
        webSettings.setAppCacheEnabled(true);
        webSettings.setDatabaseEnabled(true);
        // enable mixed content mode conditionally
        if (Constants.ENABLE_MIXED_CONTENT && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }
        // retrieve content from cache primarily if not connected
        forceCacheIfOffline();
        // set User Agent
        if (Constants.OVERRIDE_USER_AGENT || Constants.POSTFIX_USER_AGENT) {
            String userAgent = webSettings.getUserAgentString();
            if (Constants.OVERRIDE_USER_AGENT) {
                userAgent = Constants.USER_AGENT;
            }
            if (Constants.POSTFIX_USER_AGENT) {
                userAgent = userAgent + " " + Constants.USER_AGENT_POSTFIX;
            }
            webSettings.setUserAgentString(userAgent);
        }
        // enable HTML5-support
        webView.setWebChromeClient(new WebChromeClient() {

            // simple yet effective redirect/popup blocker
            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
                Message href = view.getHandler().obtainMessage();
                view.requestFocusNodeHref(href);
                final String popupUrl = href.getData().getString("url");
                if (popupUrl != null) {
                    // it's null for most rouge browser hijack ads
                    webView.loadUrl(popupUrl);
                    return true;
                }
                return false;
            }

            // update ProgressBar
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                uiManager.setLoadingProgress(newProgress);
                super.onProgressChanged(view, newProgress);
            }
        });
        // Set up Webview client
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                handleUrlLoad(view, url);
            }

            // handle loading error by showing the offline screen
            @Deprecated
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                    handleLoadError(errorCode);
                }
            }

            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    // new API method calls this on every error for each resource.
                    // we only want to interfere if the page itself got problems.
                    String url = request.getUrl().toString();
                    if (view.getUrl().equals(url)) {
                        handleLoadError(error.getErrorCode());
                    }
                }
            }
        });
    }

    // Lifecycle callbacks
    public void onPause() {
        webView.onPause();
    }

    public void onResume() {
        webView.onResume();
    }

    // show "no app found" dialog
    private void showNoAppDialog(Activity thisActivity) {
        new AlertDialog.Builder(thisActivity).setreplacedle(R.string.noapp_heading).setMessage(R.string.noapp_description).show();
    }

    // handle load errors
    private void handleLoadError(int errorCode) {
        if (errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME) {
            uiManager.setOffline(true);
        } else {
            // Unsupported Scheme, recover
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    goBack();
                }
            }, 100);
        }
    }

    // handle external urls
    private boolean handleUrlLoad(WebView view, String url) {
        // prevent loading content that isn't ours
        if (!url.startsWith(Constants.WEBAPP_URL)) {
            // stop loading
            // stopping only would cause the PWA to freeze, need to reload the app as a workaround
            view.stopLoading();
            view.reload();
            // open external URL in Browser/3rd party apps instead
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                if (intent.resolveActivity(activity.getPackageManager()) != null) {
                    activity.startActivity(intent);
                } else {
                    showNoAppDialog(activity);
                }
            } catch (Exception e) {
                showNoAppDialog(activity);
            }
            // return value for shouldOverrideUrlLoading
            return true;
        } else {
            // let WebView load the page!
            // activate loading animation screen
            uiManager.setLoading(true);
            // return value for shouldOverrideUrlLoading
            return false;
        }
    }

    // handle back button press
    public boolean goBack() {
        if (webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return false;
    }

    // load app startpage
    public void loadHome() {
        webView.loadUrl(Constants.WEBAPP_URL);
    }

    // load URL from intent
    public void loadIntentUrl(String url) {
        if (!url.equals("") && url.contains(Constants.WEBAPP_HOST)) {
            webView.loadUrl(url);
        } else {
            // Fallback
            loadHome();
        }
    }
}

19 Source : WrapWebSettings.java
with GNU General Public License v3.0
from xieyueshu

clreplaced WrapWebSettings extends WebSettings {

    private final WebSettings origin;

    WrapWebSettings(WebSettings origin) {
        this.origin = origin;
    }

    @Override
    public void setSupportZoom(boolean support) {
        origin.setSupportZoom(support);
    }

    @Override
    public boolean supportZoom() {
        return origin.supportZoom();
    }

    @Override
    public void setMediaPlaybackRequiresUserGesture(boolean require) {
        origin.setMediaPlaybackRequiresUserGesture(require);
    }

    @Override
    public boolean getMediaPlaybackRequiresUserGesture() {
        return origin.getMediaPlaybackRequiresUserGesture();
    }

    @Override
    public void setBuiltInZoomControls(boolean enabled) {
        origin.setBuiltInZoomControls(enabled);
    }

    @Override
    public boolean getBuiltInZoomControls() {
        return origin.getBuiltInZoomControls();
    }

    @Override
    public void setDisplayZoomControls(boolean enabled) {
        origin.setDisplayZoomControls(enabled);
    }

    @Override
    public boolean getDisplayZoomControls() {
        return origin.getDisplayZoomControls();
    }

    @Override
    public void setAllowFileAccess(boolean allow) {
        origin.setAllowFileAccess(allow);
    }

    @Override
    public boolean getAllowFileAccess() {
        return origin.getAllowFileAccess();
    }

    @Override
    public void setAllowContentAccess(boolean allow) {
        origin.setAllowContentAccess(allow);
    }

    @Override
    public boolean getAllowContentAccess() {
        return origin.getAllowContentAccess();
    }

    @Override
    public void setLoadWithOverviewMode(boolean overview) {
        throw new UnsupportedOperationException("If you need to disable this option, use an old WebView.");
    }

    @Override
    public boolean getLoadWithOverviewMode() {
        return origin.getLoadWithOverviewMode();
    }

    @Override
    public void setEnableSmoothTransition(boolean enable) {
        origin.setEnableSmoothTransition(enable);
    }

    @Override
    public boolean enableSmoothTransition() {
        return origin.enableSmoothTransition();
    }

    @Override
    public void setSaveFormData(boolean save) {
        origin.setSaveFormData(save);
    }

    @Override
    public boolean getSaveFormData() {
        return origin.getSaveFormData();
    }

    @Override
    public void setSavePreplacedword(boolean save) {
        origin.setSavePreplacedword(save);
    }

    @Override
    public boolean getSavePreplacedword() {
        return origin.getSavePreplacedword();
    }

    @Override
    public void setTextZoom(int textZoom) {
        origin.setTextZoom(textZoom);
    }

    @Override
    public int getTextZoom() {
        return origin.getTextZoom();
    }

    @Override
    public void setDefaultZoom(ZoomDensity zoom) {
        origin.setDefaultZoom(zoom);
    }

    @Override
    public ZoomDensity getDefaultZoom() {
        return origin.getDefaultZoom();
    }

    @Override
    public void setLightTouchEnabled(boolean enabled) {
        origin.setLightTouchEnabled(enabled);
    }

    @Override
    public boolean getLightTouchEnabled() {
        return origin.getLightTouchEnabled();
    }

    @Override
    public void setUseWideViewPort(boolean use) {
        throw new UnsupportedOperationException("If you need to disable this option, use an old WebView.");
    }

    @Override
    public boolean getUseWideViewPort() {
        return true;
    }

    @Override
    public void setSupportMultipleWindows(boolean support) {
        origin.setSupportMultipleWindows(support);
    }

    @Override
    public boolean supportMultipleWindows() {
        return origin.supportMultipleWindows();
    }

    @Override
    public void setLayoutAlgorithm(LayoutAlgorithm l) {
        origin.setLayoutAlgorithm(l);
    }

    @Override
    public LayoutAlgorithm getLayoutAlgorithm() {
        return origin.getLayoutAlgorithm();
    }

    @Override
    public void setStandardFontFamily(String font) {
        origin.setStandardFontFamily(font);
    }

    @Override
    public String getStandardFontFamily() {
        return origin.getStandardFontFamily();
    }

    @Override
    public void setFixedFontFamily(String font) {
        origin.setFixedFontFamily(font);
    }

    @Override
    public String getFixedFontFamily() {
        return origin.getFixedFontFamily();
    }

    @Override
    public void setSansSerifFontFamily(String font) {
        origin.setSansSerifFontFamily(font);
    }

    @Override
    public String getSansSerifFontFamily() {
        return origin.getSansSerifFontFamily();
    }

    @Override
    public void setSerifFontFamily(String font) {
        origin.setSerifFontFamily(font);
    }

    @Override
    public String getSerifFontFamily() {
        return origin.getSerifFontFamily();
    }

    @Override
    public void setCursiveFontFamily(String font) {
        origin.setCursiveFontFamily(font);
    }

    @Override
    public String getCursiveFontFamily() {
        return origin.getCursiveFontFamily();
    }

    @Override
    public void setFantasyFontFamily(String font) {
        origin.setFantasyFontFamily(font);
    }

    @Override
    public String getFantasyFontFamily() {
        return origin.getFantasyFontFamily();
    }

    @Override
    public void setMinimumFontSize(int size) {
        origin.setMinimumFontSize(size);
    }

    @Override
    public int getMinimumFontSize() {
        return origin.getMinimumFontSize();
    }

    @Override
    public void setMinimumLogicalFontSize(int size) {
        origin.setMinimumLogicalFontSize(size);
    }

    @Override
    public int getMinimumLogicalFontSize() {
        return origin.getMinimumLogicalFontSize();
    }

    @Override
    public void setDefaultFontSize(int size) {
        origin.setDefaultFontSize(size);
    }

    @Override
    public int getDefaultFontSize() {
        return origin.getDefaultFontSize();
    }

    @Override
    public void setDefaultFixedFontSize(int size) {
        origin.setDefaultFixedFontSize(size);
    }

    @Override
    public int getDefaultFixedFontSize() {
        return origin.getDefaultFixedFontSize();
    }

    @Override
    public void setLoadsImagesAutomatically(boolean flag) {
        origin.setLoadsImagesAutomatically(flag);
    }

    @Override
    public boolean getLoadsImagesAutomatically() {
        return origin.getLoadsImagesAutomatically();
    }

    @Override
    public void setBlockNetworkImage(boolean flag) {
        origin.setBlockNetworkImage(flag);
    }

    @Override
    public boolean getBlockNetworkImage() {
        return origin.getBlockNetworkImage();
    }

    @Override
    public void setBlockNetworkLoads(boolean flag) {
        origin.setBlockNetworkLoads(flag);
    }

    @Override
    public boolean getBlockNetworkLoads() {
        return origin.getBlockNetworkLoads();
    }

    @Override
    public void setJavaScriptEnabled(boolean flag) {
        throw new UnsupportedOperationException("If you need to disable this option, use an old WebView.");
    }

    @Override
    public void setAllowUniversalAccessFromFileURLs(boolean flag) {
        origin.setAllowUniversalAccessFromFileURLs(flag);
    }

    @Override
    public void setAllowFileAccessFromFileURLs(boolean flag) {
        origin.setAllowFileAccessFromFileURLs(flag);
    }

    @Override
    public void setPluginState(PluginState state) {
        origin.setPluginState(state);
    }

    @Override
    public void setDatabasePath(String databasePath) {
        origin.setDatabasePath(databasePath);
    }

    @Override
    public void setGeolocationDatabasePath(String databasePath) {
        origin.setGeolocationDatabasePath(databasePath);
    }

    @Override
    public void setAppCacheEnabled(boolean flag) {
        origin.setAppCacheEnabled(flag);
    }

    @Override
    public void setAppCachePath(String appCachePath) {
        origin.setAppCachePath(appCachePath);
    }

    @Override
    public void setAppCacheMaxSize(long appCacheMaxSize) {
        origin.setAppCacheMaxSize(appCacheMaxSize);
    }

    @Override
    public void setDatabaseEnabled(boolean flag) {
        origin.setDatabaseEnabled(flag);
    }

    @Override
    public void setDomStorageEnabled(boolean flag) {
        throw new UnsupportedOperationException("If you need to disable this option, use an old WebView.");
    }

    @Override
    public boolean getDomStorageEnabled() {
        return true;
    }

    @Override
    public String getDatabasePath() {
        return origin.getDatabasePath();
    }

    @Override
    public boolean getDatabaseEnabled() {
        return origin.getDatabaseEnabled();
    }

    @Override
    public void setGeolocationEnabled(boolean flag) {
        origin.setGeolocationEnabled(flag);
    }

    @Override
    public boolean getJavaScriptEnabled() {
        return true;
    }

    @Override
    public boolean getAllowUniversalAccessFromFileURLs() {
        return origin.getAllowUniversalAccessFromFileURLs();
    }

    @Override
    public boolean getAllowFileAccessFromFileURLs() {
        return origin.getAllowFileAccessFromFileURLs();
    }

    @Override
    public PluginState getPluginState() {
        return origin.getPluginState();
    }

    @Override
    public void setJavaScriptCanOpenWindowsAutomatically(boolean flag) {
        origin.setJavaScriptCanOpenWindowsAutomatically(flag);
    }

    @Override
    public boolean getJavaScriptCanOpenWindowsAutomatically() {
        return origin.getJavaScriptCanOpenWindowsAutomatically();
    }

    @Override
    public void setDefaultTextEncodingName(String encoding) {
        origin.setDefaultTextEncodingName(encoding);
    }

    @Override
    public String getDefaultTextEncodingName() {
        return origin.getDefaultTextEncodingName();
    }

    @Override
    public void setUserAgentString(@Nullable String ua) {
        origin.setUserAgentString(ua);
    }

    @Override
    public String getUserAgentString() {
        return origin.getUserAgentString();
    }

    @Override
    public void setNeedInitialFocus(boolean flag) {
        origin.setNeedInitialFocus(flag);
    }

    @Override
    public void setRenderPriority(RenderPriority priority) {
        origin.setRenderPriority(priority);
    }

    @Override
    public void setCacheMode(int mode) {
        origin.setCacheMode(mode);
    }

    @Override
    public int getCacheMode() {
        return origin.getCacheMode();
    }

    @Override
    public void setMixedContentMode(int mode) {
        throw new UnsupportedOperationException("If you need to disable this option, use an old WebView.");
    }

    @Override
    public int getMixedContentMode() {
        return MIXED_CONTENT_ALWAYS_ALLOW;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void setOffscreenPreRaster(boolean enabled) {
        origin.setOffscreenPreRaster(enabled);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public boolean getOffscreenPreRaster() {
        return origin.getOffscreenPreRaster();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void setSafeBrowsingEnabled(boolean enabled) {
        origin.setSafeBrowsingEnabled(enabled);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public boolean getSafeBrowsingEnabled() {
        return origin.getSafeBrowsingEnabled();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void setDisabledActionModeMenuItems(int menuItems) {
        origin.setDisabledActionModeMenuItems(menuItems);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public int getDisabledActionModeMenuItems() {
        return origin.getDisabledActionModeMenuItems();
    }
}

19 Source : WebViewConfig.java
with Apache License 2.0
from wzx54321

/**
 * Description :WebView Config
 * Created by 王照鑫 on 2017/11/1 0001.
 */
public clreplaced WebViewConfig implements IWebViewInit {

    private XinWebView mWebView;

    /**
     * 是否允许打电话
     */
    public static final boolean TEL_ENABLE = true;

    /**
     * 是否允许发邮件
     */
    public static final boolean MAIL_ENABLE = true;

    /**
     * 是否允许发短信
     */
    public static final boolean SMS_ENABLE = true;

    /**
     * 是否允许下载
     */
    public static final boolean DOWNLOAD_ENABLE = false;

    private SonicSessionConfig mSessionConfig;

    private WebSettings mSettings;

    private WebViewConfig() {
    }

    public static WebViewConfig getInstance() {
        return Holder.sWebViewConfig;
    }

    private static clreplaced Holder {

        protected static WebViewConfig sWebViewConfig = new WebViewConfig();
    }

    @Override
    public boolean init() {
        buildSonicEngine();
        createWebView();
        doConfig();
        return true;
    }

    /**
     * 使用webView
     */
    @Override
    public XinWebView useWebView(Context context) {
        mWebView = WebViewCache.getInstance().useWebView(context);
        if (mWebView == null) {
            mWebView = reuseWebView(context);
        }
        return mWebView;
    }

    private XinWebView reuseWebView(Context context) {
        createWebView();
        doConfig();
        if (mWebView != null) {
            ((MutableContextWrapper) mWebView.getContext()).setBaseContext(context);
            mWebView.setIsUsed(true);
        }
        return mWebView;
    }

    /**
     * 不再使用重创建
     */
    @Override
    public void resetWebView() {
        WebViewCache.getInstance().resetWebView();
        mWebView = null;
        createWebView();
        doConfig();
    }

    private void createWebView() {
        if (mWebView == null)
            mWebView = WebViewCache.getInstance().initWebView();
        if (mWebView != null) {
            Log.i("webview 初始化成功");
        }
    }

    private void doConfig() {
        if (mWebView == null)
            return;
        mSettings = initWebSettings(mWebView);
        CookiesHandler.initCookiesManager(mWebView.getContext());
        if (DOWNLOAD_ENABLE)
            mWebView.setDownloadListener(new WebDownLoadListener(mWebView.getContext()));
    }

    private void buildSonicEngine() {
        // step 1: Initialize sonic engine if necessary, or maybe u can do this when application created
        if (!SonicEngine.isGetInstanceAllowed()) {
            SonicEngine.createInstance(new XinSonicRuntime(XinApplication.getAppContext()), new SonicConfig.Builder().build());
        }
        SonicSessionConfig.Builder sessionConfigBuilder = new SonicSessionConfig.Builder();
        // sessionConfigBuilder.setSessionMode(SonicConstants.SESSION_MODE_DEFAULT);
        mSessionConfig = sessionConfigBuilder.build();
    }

    @Override
    public WebSettings initWebSettings(WebView view) {
        // 根据需求执行配置
        WebSettings setting = view.getSettings();
        // 适配
        setting.setSupportZoom(true);
        setting.setTextZoom(100);
        setting.setBuiltInZoomControls(true);
        // 隐藏缩放按钮
        setting.setDisplayZoomControls(false);
        setting.setUseWideViewPort(true);
        setting.setLoadWithOverviewMode(true);
        if (SysUtils.hasKitKat()) {
            setting.setLayoutAlgorithm(android.webkit.WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        } else {
            setting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        }
        // 存储
        // setting.setSavePreplacedword(true);
        setting.setSaveFormData(true);
        // 允许加载本地文件html  file协议
        setting.setAllowFileAccess(true);
        setting.setDefaultTextEncodingName("UTF-8");
        setting.setDomStorageEnabled(true);
        setting.setDatabaseEnabled(true);
        setting.setAppCacheEnabled(true);
        // 定位
        // 启用地理定位
        setting.setGeolocationEnabled(true);
        String dir = getCacheDir(view.getContext());
        // 设置H5缓存
        setting.setAppCachePath(dir);
        if (!SysUtils.hasKitKat()) {
            // 设置数据库路径  api19 已经废弃,这里只针对 webkit 起作用
            setting.setGeolocationDatabasePath(dir);
            setting.setDatabasePath(dir);
            // 缓存文件最大值
            setting.setAppCacheMaxSize(Long.MAX_VALUE);
        }
        // 根据cache-control获取数据。
        setting.setCacheMode(android.webkit.WebSettings.LOAD_DEFAULT);
        if (SysUtils.hasKitKat()) {
            // 图片自动缩放 打开
            setting.setLoadsImagesAutomatically(true);
        } else {
            // 图片自动缩放 关闭
            setting.setLoadsImagesAutomatically(false);
        }
        setting.setSupportMultipleWindows(false);
        // 是否阻塞加载网络图片  协议http or https
        setting.setBlockNetworkImage(false);
        setting.setNeedInitialFocus(true);
        setting.setJavaScriptCanOpenWindowsAutomatically(true);
        setting.setDefaultFontSize(16);
        // 设置 WebView 支持的最小字体大小,默认为 8
        setting.setMinimumFontSize(12);
        setting.setJavaScriptEnabled(true);
        if (SysUtils.hasLollipop()) {
            // 适配5.0不允许http和https混合使用情况
            setting.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        } else if (SysUtils.hasKitKat()) {
            view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        } else if (!SysUtils.hasKitKat()) {
            view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        view.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_INSET);
        view.setSaveEnabled(true);
        // view.setKeepScreenOn(true);
        /* TODO 还没有使用sonic的接口   // add java script interface
         // sonic 使用的
        view.removeJavascriptInterface("searchBoxJavaBridge_");
        intent.putExtra(SonicJavaScriptInterface.PARAM_LOAD_URL_TIME, System.currentTimeMillis());
        view.addJavascriptInterface(new SonicJavaScriptInterface(sonicSessionClient, intent), "sonic");*/
        return setting;
    }

    @Override
    public String getCacheDir(Context context) {
        return context.getCacheDir().getAbsolutePath() + File.separator + FileConfig.DIR_WEB_CACHE;
    }

    @Override
    public File getSonicCacheDir(Context context) {
        String dir = context.getFilesDir().getAbsolutePath() + File.separator + FileConfig.DIR_WEB_SONIC_CACHE;
        File file = new File(dir);
        FileUtil.createDir(file);
        return file;
    }

    @SuppressLint("JavascriptInterface")
    @Override
    public void addJavascriptInterface(Object object, String name) {
        mWebView.addJavascriptInterface(object, name);
    }

    @Override
    public void clearWebCache(boolean mIsWebViewInit) {
        WebViewCache.getInstance().clearWebCache(mIsWebViewInit);
    }

    @Override
    public void checkCacheMode() {
        if (Network.isAvailable(mWebView.getContext())) {
            // 根据cache-control获取数据。
            getSettings().setCacheMode(android.webkit.WebSettings.LOAD_DEFAULT);
        } else {
            // 没网,则从本地获取,即离线加载
            getSettings().setCacheMode(android.webkit.WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
    }

    public SonicSessionConfig getSessionConfig() {
        return mSessionConfig;
    }

    public WebSettings getSettings() {
        return mSettings;
    }
}

19 Source : SimpleWebView.java
with Apache License 2.0
from Qihoo360

public String getUserAgentEx() {
    if (sUserAgent == null) {
        WebSettings ws = getSettings();
        sUserAgent = ws.getUserAgentString();
    }
    // 此处可自定义自己的UserAgent
    return sUserAgent;
}

19 Source : LightningView.java
with GNU General Public License v2.0
from NewCasino

// http://blog.sina.com.cn/s/blog_49f62c3501013ygb.html
void setPageCacheCapacity(WebSettings webSettings) {
    try {
        Object[] args = { Integer.valueOf(5) };
        Method m = WebSettings.clreplaced.getMethod("setPageCacheCapacity", new Clreplaced[] { int.clreplaced });
        m.setAccessible(true);
        // wSettings是WebSettings对象
        m.invoke(webSettings, args);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

19 Source : LightningView.java
with GNU General Public License v2.0
from NewCasino

void setPageCacheCapacity2(WebSettings webSettings) {
    try {
        // android.webkit.WebSettings
        Clreplaced<?> c = Clreplaced.forName("android.webkit.WebSettingsClreplacedic");
        Method tt = c.getMethod("setPageCacheCapacity", new Clreplaced[] { int.clreplaced });
        tt.invoke(webSettings, 5);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

19 Source : HelpActivity.java
with GNU Affero General Public License v3.0
from mirfatif

public clreplaced HelpActivity extends BaseActivity {

    private WebSettings mWebSettings;

    private final MySettings mMySettings = MySettings.getInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_help);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setreplacedle(R.string.help_menu_item);
        }
        WebView webView = findViewById(R.id.help_web_view);
        mWebSettings = webView.getSettings();
        mFontSize = mMySettings.getIntPref(R.string.pref_help_font_size_key);
        setFontSize();
        mWebSettings.setSupportZoom(false);
        mWebSettings.setBlockNetworkLoads(true);
        webView.setWebViewClient(new MyWebViewClient());
        enableJs();
        webView.addJavascriptInterface(new HelpJsInterface(this), "Android");
        webView.loadUrl("file:///android_replacedet/help.html");
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void enableJs() {
        mWebSettings.setJavaScriptEnabled(true);
    }

    private int mFontSize;

    private void setFontSize() {
        mWebSettings.setDefaultFontSize(mFontSize);
        if (mFontSize > 22 || mFontSize < 12) {
            invalidateOptionsMenu();
        }
        mMySettings.savePref(R.string.pref_help_font_size_key, mFontSize);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.help_zoom, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.action_zoom_in).setEnabled(mFontSize < 24);
        menu.findItem(R.id.action_zoom_out).setEnabled(mFontSize > 10);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.gereplacedemId() == R.id.action_zoom_in) {
            mFontSize++;
            setFontSize();
            return true;
        }
        if (item.gereplacedemId() == R.id.action_zoom_out) {
            mFontSize--;
            setFontSize();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private clreplaced MyWebViewClient extends WebViewClientCompat {

        @Override
        public boolean shouldOverrideUrlLoading(@NonNull WebView view, WebResourceRequest request) {
            String url = request.getUrl().toString();
            if (url.startsWith("http://") || url.startsWith("https://")) {
                Utils.openWebUrl(HelpActivity.this, url);
                return true;
            }
            if (url.startsWith("activity://") && url.contains("about")) {
                startActivity(new Intent(App.getContext(), AboutActivity.clreplaced));
                return true;
            }
            return super.shouldOverrideUrlLoading(view, request);
        }
    }
}

19 Source : AbsAgentWebSettings.java
with Apache License 2.0
from Justson

/**
 * @author cenxiaozhong
 * @update 4.0.0 ,WebDefaultSettingsManager rename to AbsAgentWebSettings
 * @since 1.0.0
 */
public abstract clreplaced AbsAgentWebSettings implements IAgentWebSettings, WebListenerManager {

    private WebSettings mWebSettings;

    private static final String TAG = AbsAgentWebSettings.clreplaced.getSimpleName();

    public static final String USERAGENT_UC = " UCBrowser/11.6.4.950 ";

    public static final String USERAGENT_QQ_BROWSER = " MQQBrowser/8.0 ";

    public static final String USERAGENT_AGENTWEB = " " + AgentWebConfig.AGENTWEB_VERSION + " ";

    protected AgentWeb mAgentWeb;

    public static AbsAgentWebSettings getInstance() {
        return new AgentWebSettingsImpl();
    }

    public AbsAgentWebSettings() {
    }

    final void bindAgentWeb(AgentWeb agentWeb) {
        this.mAgentWeb = agentWeb;
        this.bindAgentWebSupport(agentWeb);
    }

    protected abstract void bindAgentWebSupport(AgentWeb agentWeb);

    @Override
    public IAgentWebSettings toSetting(WebView webView) {
        settings(webView);
        return this;
    }

    private void settings(WebView webView) {
        mWebSettings = webView.getSettings();
        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setSupportZoom(true);
        mWebSettings.setBuiltInZoomControls(false);
        mWebSettings.setSavePreplacedword(false);
        if (AgentWebUtils.checkNetwork(webView.getContext())) {
            // 根据cache-control获取数据。
            mWebSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        } else {
            // 没网,则从本地获取,即离线加载
            mWebSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // 适配5.0不允许http和https混合使用情况
            mWebSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        mWebSettings.setTextZoom(100);
        mWebSettings.setDatabaseEnabled(true);
        mWebSettings.setAppCacheEnabled(true);
        mWebSettings.setLoadsImagesAutomatically(true);
        mWebSettings.setSupportMultipleWindows(false);
        // 是否阻塞加载网络图片  协议http or https
        mWebSettings.setBlockNetworkImage(false);
        // 允许加载本地文件html  file协议
        mWebSettings.setAllowFileAccess(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            // 通过 file url 加载的 Javascript 读取其他的本地文件 .建议关闭
            mWebSettings.setAllowFileAccessFromFileURLs(false);
            // 允许通过 file url 加载的 Javascript 可以访问其他的源,包括其他的文件和 http,https 等其他的源
            mWebSettings.setAllowUniversalAccessFromFileURLs(false);
        }
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        } else {
            mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        }
        mWebSettings.setLoadWithOverviewMode(false);
        mWebSettings.setUseWideViewPort(false);
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setNeedInitialFocus(true);
        // 设置编码格式
        mWebSettings.setDefaultTextEncodingName("utf-8");
        mWebSettings.setDefaultFontSize(16);
        // 设置 WebView 支持的最小字体大小,默认为 8
        mWebSettings.setMinimumFontSize(12);
        mWebSettings.setGeolocationEnabled(true);
        String dir = AgentWebConfig.getCachePath(webView.getContext());
        LogUtils.i(TAG, "dir:" + dir + "   appcache:" + AgentWebConfig.getCachePath(webView.getContext()));
        // 设置数据库路径  api19 已经废弃,这里只针对 webkit 起作用
        mWebSettings.setGeolocationDatabasePath(dir);
        mWebSettings.setDatabasePath(dir);
        mWebSettings.setAppCachePath(dir);
        // 缓存文件最大值
        mWebSettings.setAppCacheMaxSize(Long.MAX_VALUE);
        mWebSettings.setUserAgentString(getWebSettings().getUserAgentString().concat(USERAGENT_AGENTWEB).concat(USERAGENT_UC));
        LogUtils.i(TAG, "UserAgentString : " + mWebSettings.getUserAgentString());
    }

    @Override
    public WebSettings getWebSettings() {
        return mWebSettings;
    }

    @Override
    public WebListenerManager setWebChromeClient(WebView webview, WebChromeClient webChromeClient) {
        webview.setWebChromeClient(webChromeClient);
        return this;
    }

    @Override
    public WebListenerManager setWebViewClient(WebView webView, WebViewClient webViewClient) {
        webView.setWebViewClient(webViewClient);
        return this;
    }

    @Override
    public WebListenerManager setDownloader(WebView webView, DownloadListener downloadListener) {
        webView.setDownloadListener(downloadListener);
        return this;
    }
}

19 Source : ViewWebsiteFragment.java
with MIT License
from appsecco

/**
 * A simple {@link Fragment} subclreplaced.
 */
public clreplaced ViewWebsiteFragment extends Fragment {

    public static WebView wv_personal_website;

    public static WebSettings webSettings;

    public ViewWebsiteFragment() {
    // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.view_website_fragment, container, false);
        wv_personal_website = (WebView) view.findViewById(R.id.wv_personal_website);
        Bundle bundle = getArguments();
        String URL = bundle.getString("URL");
        // Check if URL begins with http
        if (!URL.matches("^(http|https)://.*$")) {
            URL = "http://" + URL;
        }
        wv_personal_website.setWebViewClient(new WebViewClient());
        webSettings = wv_personal_website.getSettings();
        webSettings.setJavaScriptEnabled(true);
        wv_personal_website.setWebChromeClient(new WebChromeClient());
        // wv_personal_website.getSettings().setJavaScriptEnabled(true);
        // wv_personal_website.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        // wv_personal_website.canGoBack();
        // wv_personal_website.goBack();
        // If URL is valid, open it
        if (URLUtil.isValidUrl(URL)) {
            wv_personal_website.loadUrl(URL);
        } else // If URL is invalid
        {
            // Show a custom display_data_from_db webpage
            String htmlData = "<html><body><div align=\"center\" ><h2> Error loading URL: </h2><p>The link you are trying to access seems to be invalid. Please correct the URL and try again. </p><span style=\"color:red\"><h3><br/>" + URL + "</h3></span></div></body>";
            wv_personal_website.loadUrl("about:blank");
            wv_personal_website.loadDataWithBaseURL(null, htmlData, "text/html", "UTF-8", null);
            wv_personal_website.invalidate();
        }
        wv_personal_website.setWebViewClient(new WebViewClient());
        return view;
    }
}

19 Source : WebSettingsCompat.java
with Apache License 2.0
from androidx

private static WebSettingsAdapter getAdapter(WebSettings settings) {
    return WebViewGlueCommunicator.getCompatConverter().convertSettings(settings);
}

19 Source : WebkitToCompatConverter.java
with Apache License 2.0
from androidx

/**
 * Return a WebSettingsAdapter linked to webSettings such that calls on either of those
 * objects affect the other object. That WebSettingsAdapter can be used to implement
 * {@link androidx.webkit.WebSettingsCompat}.
 */
@NonNull
public WebSettingsAdapter convertSettings(WebSettings webSettings) {
    return new WebSettingsAdapter(BoundaryInterfaceReflectionUtil.castToSuppLibClreplaced(WebSettingsBoundaryInterface.clreplaced, mImpl.convertSettings(webSettings)));
}

18 Source : ConfigEditFragment.java
with GNU Lesser General Public License v3.0
from ZaneYork

@SuppressLint("SetJavaScriptEnabled")
private void initreplacedetWebView() {
    final WebViewreplacedetLoader replacedetLoader = new WebViewreplacedetLoader.Builder().addPathHandler("/replacedets/", new WebViewreplacedetLoader.replacedetsPathHandler(this.requireContext())).build();
    binding.editTextConfigWebview.setWebViewClient(new WebViewClient() {

        @Override
        @RequiresApi(21)
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            return replacedetLoader.shouldInterceptRequest(request.getUrl());
        }

        @Override
        // for API < 21
        @SuppressWarnings("deprecation")
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            return replacedetLoader.shouldInterceptRequest(Uri.parse(url));
        }
    });
    WebSettings webViewSettings = binding.editTextConfigWebview.getSettings();
    webViewSettings.setAllowFileAccess(false);
    webViewSettings.setAllowContentAccess(false);
    webViewSettings.setJavaScriptEnabled(true);
}

18 Source : NewsDetailFragment.java
with MIT License
from ZafraniTechLLC

private void setWebView(@NonNull final String newsSrc) {
    if (newsWebView != null) {
        WebSettings settings = this.newsWebView.getSettings();
        settings.setUseWideViewPort(true);
        settings.setBuiltInZoomControls(true);
        settings.setLoadWithOverviewMode(true);
        this.newsWebView.loadUrl(newsSrc);
    }
}

18 Source : ChatRecommendDetailActivity.java
with GNU General Public License v3.0
from YangChengTeam

private void initWebView(String data) {
    WebSettings settings = webView.getSettings();
    // 设置js接口
    webView.addJavascriptInterface(new AndroidJavaScript(), "android");
    // 支持内容重新布局
    settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    webView.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            webView.loadUrl("javascript:window.APP.resize(doreplacedent.body.getScrollHeight())");
        }
    });
}

18 Source : Html5Activity.java
with Apache License 2.0
from xxyangyoulin

/**
 * 多窗口的问题
 */
private void newWin(WebSettings mWebSettings) {
    // html中的_bank标签就是新建窗口打开,有时会打不开,需要加以下
    // 然后 复写 WebChromeClient的onCreateWindow方法
    mWebSettings.setSupportMultipleWindows(false);
    mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
}

18 Source : WebBrowse.java
with Apache License 2.0
from xiaolutang

protected void init() {
    WebSettings settings = getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setTextZoom(100);
    // 将图片调整到适合webview的大小
    settings.setUseWideViewPort(true);
    // 缩放至屏幕的大小
    settings.setLoadWithOverviewMode(true);
    setBackgroundColor(0);
}

18 Source : ShowMapFragment.java
with GNU General Public License v2.0
from videgro

@SuppressLint("SetJavaScriptEnabled")
private void setupWebView(final View rootView) {
    webView = (WebView) rootView.findViewById(R.id.webview);
    // Enable JavaScript on webview
    final WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setAllowFileAccessFromFileURLs(true);
    webView.addJavascriptInterface(new JavaScriptInterface(), "android");
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            webView.loadUrl("javascript:init()");
            webView.loadUrl("javascript:setZoomToExtent(" + Boolean.toString(SettingsUtils.getInstance().parseFromPreferencesMapZoomToExtent()) + ")");
            webView.loadUrl("javascript:setPrefetchLowerZoomLevelsTiles(" + Boolean.toString(SettingsUtils.getInstance().parseFromPreferencesMapCacheLowerZoomlevels()) + ")");
            webView.loadUrl("javascript:setDisableSound(" + Boolean.toString(SettingsUtils.getInstance().parseFromPreferencesMapDisableSound()) + ")");
            webView.loadUrl("javascript:setShipScaleFactor(" + SettingsUtils.getInstance().parseFromPreferencesShipScaleFactor() + ")");
            webView.loadUrl("javascript:setMaxAge(" + SettingsUtils.getInstance().parseFromPreferencesMaxAge() + ")");
            webView.loadUrl("javascript:setOwnLocationIcon('" + SettingsUtils.getInstance().parseFromPreferencesOwnLocationIcon() + "')");
            if (lastReceivedOwnLocation != null) {
                webView.loadUrl("javascript:setCurrentPosition(" + lastReceivedOwnLocation.getLongitude() + "," + lastReceivedOwnLocation.getLareplacedude() + ")");
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            boolean result = false;
            if (url != null && url.contains(PLACEHOLDER_MMSI)) {
                final String mmsi = url.split(PLACEHOLDER_MMSI)[1];
                final String newUrl = getString(R.string.url_mmsi_info).replace(PLACEHOLDER_MMSI, mmsi);
                replacedytics.logEvent(getActivity(), TAG, "shipinfo", mmsi);
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(newUrl)));
                result = true;
            }
            return result;
        }
    });
}

18 Source : ScrapingWebViewBase.java
with MIT License
from Scraper-Club

@SuppressLint("SetJavaScriptEnabled")
protected void setupSettings() {
    WebSettings settings = getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setUserAgentString(settings.getUserAgentString().replaceAll("(?i)mobile", ""));
}

18 Source : NewsDetailsActivity.java
with GNU General Public License v3.0
from SamuelGjk

@Override
protected void onDestroy() {
    WebSettings settings = postContent.getSettings();
    settings.setJavaScriptEnabled(false);
    postContent.destroy();
    super.onDestroy();
}

18 Source : DWebView.java
with GNU General Public License v3.0
from plusend

@Override
public void destroy() {
    setWebViewClient(null);
    WebSettings settings = getSettings();
    settings.setJavaScriptEnabled(false);
    removeJavascriptInterface("mWebViewImageListener");
    removeAllViewsInLayout();
    removeAllViews();
    // clearCache(true);
    super.destroy();
}

18 Source : EchartView.java
with Apache License 2.0
from openXu

private void init() {
    WebSettings webSettings = getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    webSettings.setSupportZoom(false);
    webSettings.setDisplayZoomControls(false);
    loadUrl("file:///android_replacedet/echarts.html");
}

18 Source : MainActivity.java
with MIT License
from mcuking

public clreplaced MainActivity extends AppCompatActivity {

    private DWebView mWebview;

    private WebSettings mWebSettings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
        getWindow().getDecorView().setSystemUiVisibility(option);
        // 设置状态栏背景色和字体颜色
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimary));
        // 请求获取日历权限
        requestPermission();
        mWebview = (DWebView) findViewById(R.id.mWebview);
        // 向 js 环境注入 ds_bridge
        mWebview.addJavascriptObject(new JsApi(), null);
        // 复写 WebviewClient 类
        mWebview.setWebViewClient(new OfflineWebViewClient());
        // 可复写 WebviewChromeClient
        mWebview.setWebChromeClient(new WebChromeClient());
        mWebSettings = mWebview.getSettings();
        // 如果访问的页面中要与Javascript交互,则WebView必须设置支持Javascript
        mWebSettings.setJavaScriptEnabled(true);
        // 开启DOM缓存
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setDatabaseEnabled(true);
        // 使用WebView中缓存
        mWebSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        // 支持 Chrome 调试
        mWebview.setWebContentsDebuggingEnabled(true);
        // 获取 app 版本
        PackageManager packageManager = getPackageManager();
        PackageInfo packInfo = null;
        try {
            // getPackageName()是你当前类的包名,0代表是获取版本信息
            packInfo = packageManager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String appVersion = packInfo.versionName;
        // 获取系统版本
        String systemVersion = android.os.Build.VERSION.RELEASE;
        mWebSettings.setUserAgentString(mWebSettings.getUserAgentString() + " DSBRIDGE_" + appVersion + "_" + systemVersion + "_android");
        mWebview.loadUrl("http://122.51.132.117/");
    }

    // 复写安卓返回事件 转为响应 h5 返回
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebview.canGoBack()) {
            mWebview.goBack();
            return true;
        } else {
            this.finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    // 请求获取日历权限
    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR }, 0);
    }
}

18 Source : WebViewFallbackActivity.java
with Apache License 2.0
from GoogleChrome

@SuppressLint("SetJavaScriptEnabled")
private static void setupWebSettings(WebSettings webSettings) {
    // Those settings are disabled by default.
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setDatabaseEnabled(true);
}

18 Source : NestedWebView.java
with Apache License 2.0
from Freelander

/**
 * Created by Jun on 2016/10/20.
 */
public clreplaced NestedWebView extends WebView implements NestedScrollingChild {

    private static final int INVALID_POINTER = -1;

    private static String TAG = NestedWebView.clreplaced.getSimpleName();

    private final int[] mScrollConsumed = new int[2];

    private final int[] mScrollOffset = new int[2];

    public int direction = 0;

    public ScrollStateChangedListener.ScrollState position = ScrollStateChangedListener.ScrollState.TOP;

    int preContentHeight = 0;

    private int consumedY;

    private int contentHeight = -1;

    private float density;

    private DirectionDetector directionDetector;

    private NestedScrollingChildHelper mChildHelper;

    private OnLongClickListener longClickListenerFalse;

    private OnLongClickListener longClickListenerTrue;

    private boolean mIsBeingDragged = false;

    private int mMaximumVelocity;

    private int mMinimumVelocity;

    private int mNestedYOffset;

    private int mLastMotionY;

    private int mActivePointerId = -1;

    private VelocityTracker mVelocityTracker;

    private OnScrollChangeListener onScrollChangeListener;

    private int originHeight;

    private ViewGroup parentView;

    private float preY;

    private ScrollStateChangedListener scrollStateChangedListener;

    private WebSettings settings;

    private int mTouchSlop;

    private int webviewHeight = -1;

    public NestedWebView(Context paramContext) {
        this(paramContext, null);
    }

    public NestedWebView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public NestedWebView(Context paramContext, AttributeSet paramAttributeSet, int paramInt) {
        super(paramContext, paramAttributeSet, paramInt);
        init();
    }

    private void endTouch() {
        setJavaScriptEnable(true);
        this.mIsBeingDragged = false;
        this.mActivePointerId = -1;
        recycleVelocityTracker();
        stopNestedScroll();
    }

    private void flingWithNestedDispatch(int velocityY) {
        if (!dispatchNestedPreFling(0.0F, velocityY)) {
            Log.i(TAG, "dispatchNestedPreFling : velocityY : " + velocityY);
            dispatchNestedFling(0, velocityY, true);
        // flingScroll(0,velocityY);
        }
    }

    private void getEmbeddedParent(View paramView) {
        ViewParent localViewParent = paramView.getParent();
        if (localViewParent != null) {
            if ((localViewParent instanceof ScrollStateChangedListener)) {
                this.parentView = ((ViewGroup) localViewParent);
                setScrollStateChangedListener((ScrollStateChangedListener) localViewParent);
            } else {
                if ((localViewParent instanceof ViewGroup)) {
                    getEmbeddedParent((ViewGroup) localViewParent);
                }
            }
        }
    }

    private void init() {
        this.mChildHelper = new NestedScrollingChildHelper(this);
        setNestedScrollingEnabled(true);
        ViewConfiguration configuration = ViewConfiguration.get(getContext());
        this.mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
        this.mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
        this.mTouchSlop = configuration.getScaledTouchSlop();
        this.directionDetector = new DirectionDetector();
        this.density = getScale();
        setOverScrollMode(View.OVER_SCROLL_NEVER);
        this.settings = getSettings();
        // addJavascriptInterface(new JSGetContentHeight(), "InjectedObject");
        Log.i(TAG, "max -- min Velocity = " + this.mMaximumVelocity + " -- " + this.mMinimumVelocity + " touchSlop = " + this.mTouchSlop);
    }

    private void setJavaScriptEnable(boolean flag) {
        if (this.settings.getJavaScriptEnabled() != flag) {
            Log.i(TAG, "setJavaScriptEnable : " + this.settings.getJavaScriptEnabled() + " / " + flag);
            this.settings.setJavaScriptEnabled(flag);
        }
    }

    private void setScrollStateChangedListener(ScrollStateChangedListener paramc) {
        this.scrollStateChangedListener = paramc;
    }

    @Override
    public void computeScroll() {
        if (this.position == ScrollStateChangedListener.ScrollState.MIDDLE) {
            super.computeScroll();
        }
    }

    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
        return this.mChildHelper.dispatchNestedFling(velocityX, velocityY, consumed);
    }

    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
        return this.mChildHelper.dispatchNestedPreFling(velocityX, velocityY);
    }

    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
        return this.mChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow);
    }

    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
        return this.mChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow);
    }

    public int getWebContentHeight() {
        return this.contentHeight;
    }

    public boolean hasNestedScrollingParent() {
        return this.mChildHelper.hasNestedScrollingParent();
    }

    @Override
    public void invalidate() {
        super.invalidate();
        this.contentHeight = ((int) (getContentHeight() * getScale()));
        if (this.contentHeight != this.preContentHeight) {
            loadUrl("javascript:window.InjectedObject.getContentHeight(doreplacedent.getElementsByTagName('div')[0].scrollHeight)");
            this.preContentHeight = this.contentHeight;
        }
    }

    public boolean isBeingDragged() {
        return this.mIsBeingDragged;
    }

    public boolean isNestedScrollingEnabled() {
        return this.mChildHelper.isNestedScrollingEnabled();
    }

    @Override
    public void setNestedScrollingEnabled(boolean paramBoolean) {
        this.mChildHelper.setNestedScrollingEnabled(paramBoolean);
    }

    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        getEmbeddedParent(this);
    }

    private void setLongClickEnable(boolean longClickable) {
        if (longClickable) {
            Log.i(TAG, "111111 setLongClickEnable : " + isLongClickable());
            if (!isLongClickable()) {
                super.setOnLongClickListener(this.longClickListenerFalse);
                setLongClickable(true);
                setHapticFeedbackEnabled(true);
            }
            return;
        }
        Log.i(TAG, "22222 setLongClickEnable : " + isLongClickable());
        if (this.longClickListenerTrue == null) {
            this.longClickListenerTrue = new OnLongClickListener() {

                public boolean onLongClick(View view) {
                    return true;
                }
            };
        }
        super.setOnLongClickListener(this.longClickListenerTrue);
        setLongClickable(false);
        setHapticFeedbackEnabled(false);
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldx, int oldy) {
        super.onScrollChanged(x, y, oldx, oldy);
        this.consumedY = (y - oldy);
        Log.i(TAG, "consumedYconsumedYconsumedY====" + consumedY);
        if (y <= 0) {
            this.position = ScrollStateChangedListener.ScrollState.TOP;
            return;
        }
        if (null != this.scrollStateChangedListener) {
            this.scrollStateChangedListener.onChildPositionChange(this.position);
        }
        if (this.onScrollChangeListener != null) {
            this.onScrollChangeListener.onScrollChanged(x, y, oldx, oldy, this.position);
        } else {
            // Log.i(TAG,"yy=="+y+"  webviewHeight=="+this.webviewHeight+"  contentHeight=="+this.contentHeight);
            if (y + this.webviewHeight >= this.contentHeight) {
                if (this.contentHeight > 0) {
                    this.position = ScrollStateChangedListener.ScrollState.BOTTOM;
                }
            } else {
                this.position = ScrollStateChangedListener.ScrollState.MIDDLE;
            }
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        this.webviewHeight = h + 1;
        if (this.contentHeight < 1) {
            setContentHeight(this.webviewHeight);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (this.position == ScrollStateChangedListener.ScrollState.MIDDLE) {
            switch(ev.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    {
                        this.mIsBeingDragged = false;
                        this.mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
                        this.startNestedScroll(2);
                        break;
                    }
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    {
                        this.endTouch();
                        break;
                    }
            }
            super.onTouchEvent(ev);
            return true;
        }
        final int actionMasked = MotionEventCompat.getActionMasked(ev);
        initVelocityTrackerIfNotExists();
        MotionEvent vtev = MotionEvent.obtain(ev);
        final int index = MotionEventCompat.getActionIndex(ev);
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            mNestedYOffset = 0;
        }
        vtev.offsetLocation(0, mNestedYOffset);
        this.consumedY = 0;
        this.direction = 0;
        boolean onTouchEvent = false;
        switch(actionMasked) {
            case MotionEvent.ACTION_DOWN:
                {
                    // Remember where the motion event started
                    onTouchEvent = super.onTouchEvent(ev);
                    mLastMotionY = (int) (ev.getY() + 0.5f);
                    mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
                    this.preY = vtev.getY();
                    this.mIsBeingDragged = false;
                    startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL);
                    break;
                }
            case MotionEventCompat.ACTION_POINTER_DOWN:
                {
                    onTouchEvent = super.onTouchEvent(ev);
                    mLastMotionY = (int) (MotionEventCompat.getY(ev, index) + 0.5f);
                    mActivePointerId = MotionEventCompat.getPointerId(ev, index);
                    break;
                }
            case MotionEvent.ACTION_MOVE:
                final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
                if (activePointerIndex == -1) {
                    Log.e(TAG, "Invalid pointerId=" + mActivePointerId + " in onTouchEvent");
                    break;
                }
                if (!mIsBeingDragged && Math.abs(vtev.getY() - this.preY) > mTouchSlop) {
                    final ViewParent parent = getParent();
                    if (parent != null) {
                        parent.requestDisallowInterceptTouchEvent(true);
                    }
                    mIsBeingDragged = true;
                }
                // if(!mIsBeingDragged){
                // setLongClickEnable(true);
                // }
                final int y = (int) (MotionEventCompat.getY(ev, activePointerIndex) + 0.5f);
                Log.i(TAG, "mLastMotionY=====" + mLastMotionY);
                Log.i(TAG, "YYYYYYY=====" + y);
                int deltaY = mLastMotionY - y;
                if (deltaY != 0) {
                    this.direction = this.directionDetector.getDirection(deltaY, true, this.scrollStateChangedListener);
                }
                if (dispatchNestedPreScroll(0, deltaY, mScrollConsumed, mScrollOffset)) {
                    deltaY -= mScrollConsumed[1];
                    vtev.offsetLocation(0, mScrollOffset[1]);
                    mNestedYOffset += mScrollOffset[1];
                }
                if (mIsBeingDragged) {
                    // setJavaScriptEnable(true);
                    // Scroll to follow the motion event
                    mLastMotionY = y - mScrollOffset[1];
                    Log.i(TAG, "deltaY===" + deltaY);
                    Log.i(TAG, "this.consumedY===" + this.consumedY);
                    final int unconsumedY = deltaY - this.consumedY;
                    Log.i(TAG, " child consumed = " + this.mScrollConsumed[1] + " un_consumed = " + unconsumedY + " position = " + this.position + " direction = " + this.direction);
                    onTouchEvent = super.onTouchEvent(ev);
                    if (this.position == ScrollStateChangedListener.ScrollState.MIDDLE) {
                        return true;
                    }
                    switch(this.direction) {
                        case 1:
                            {
                                if ((this.position != ScrollStateChangedListener.ScrollState.BOTTOM) && (this.contentHeight != this.webviewHeight)) {
                                    scrollBy(0, unconsumedY);
                                    break;
                                }
                                Log.i(TAG, "1111111consumedY===" + consumedY + "  unconsumedY==" + unconsumedY);
                                if (dispatchNestedScroll(0, this.consumedY, 0, unconsumedY, this.mScrollOffset)) {
                                    vtev.offsetLocation(0.0F, this.mScrollOffset[1]);
                                    this.mNestedYOffset += this.mScrollOffset[1];
                                    this.mLastMotionY -= this.mScrollOffset[1];
                                }
                            }
                            break;
                        case 2:
                            if ((this.position == ScrollStateChangedListener.ScrollState.TOP) || (this.contentHeight == this.webviewHeight)) {
                                Log.i(TAG, "2222222consumedY===" + consumedY + "  unconsumedY==" + unconsumedY);
                                if (dispatchNestedScroll(0, this.consumedY, 0, unconsumedY, this.mScrollOffset)) {
                                    vtev.offsetLocation(0.0F, this.mScrollOffset[1]);
                                    this.mNestedYOffset += this.mScrollOffset[1];
                                    this.mLastMotionY -= this.mScrollOffset[1];
                                }
                            } else {
                                scrollBy(0, unconsumedY);
                            }
                            break;
                        default:
                            break;
                    }
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                onTouchEvent = super.onTouchEvent(ev);
                break;
            case MotionEvent.ACTION_UP:
                onTouchEvent = super.onTouchEvent(ev);
                if (mIsBeingDragged) {
                    final VelocityTracker velocityTracker = mVelocityTracker;
                    velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
                    int initialVelocity = (int) VelocityTrackerCompat.getYVelocity(velocityTracker, mActivePointerId);
                    if ((Math.abs(initialVelocity) > mMinimumVelocity)) {
                        flingWithNestedDispatch(-initialVelocity);
                    }
                }
                mActivePointerId = INVALID_POINTER;
                endTouch();
                break;
            case MotionEventCompat.ACTION_POINTER_UP:
                onTouchEvent = super.onTouchEvent(ev);
                onSecondaryPointerUp(ev);
                mLastMotionY = (int) (MotionEventCompat.getY(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId)) + 0.5F);
                break;
        }
        if (mVelocityTracker != null) {
            mVelocityTracker.addMovement(vtev);
        }
        vtev.recycle();
        return onTouchEvent;
    }

    private void onSecondaryPointerUp(MotionEvent ev) {
        final int pointerIndex = (ev.getAction() & MotionEventCompat.ACTION_POINTER_INDEX_MASK) >> MotionEventCompat.ACTION_POINTER_INDEX_SHIFT;
        final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
        if (pointerId == mActivePointerId) {
            // This was our active pointer going up. Choose getDirection new
            // active pointer and adjust accordingly.
            // TODO: Make this decision more intelligent.
            final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
            mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
            if (mVelocityTracker != null) {
                mVelocityTracker.clear();
            }
        }
    }

    private void initOrResetVelocityTracker() {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        } else {
            mVelocityTracker.clear();
        }
    }

    private void initVelocityTrackerIfNotExists() {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
    }

    private void recycleVelocityTracker() {
        if (mVelocityTracker != null) {
            mVelocityTracker.recycle();
            mVelocityTracker = null;
        }
    }

    @Override
    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
        if (disallowIntercept) {
            recycleVelocityTracker();
        }
        super.requestDisallowInterceptTouchEvent(disallowIntercept);
    }

    @Override
    protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {
        if (this.position != ScrollStateChangedListener.ScrollState.MIDDLE) {
            deltaY = 0;
        }
        return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);
    }

    public void scrollToBottom() {
        scrollTo(getScrollX(), this.contentHeight - this.webviewHeight);
    }

    public void scrollToTop() {
        scrollTo(getScrollX(), 0);
    }

    public void setContentHeight(int contentHeight) {
        this.contentHeight = contentHeight;
        Log.i(TAG, "contentHeight = " + contentHeight + " -  webviewHeight = " + this.webviewHeight + " = " + (contentHeight - this.webviewHeight));
    }

    public void setOnLongClickListener(OnLongClickListener mOnLongClickListener) {
        this.longClickListenerFalse = mOnLongClickListener;
        super.setOnLongClickListener(mOnLongClickListener);
    }

    public void setOnScrollChangeListener(OnScrollChangeListener paramOnScrollChangeListener) {
        this.onScrollChangeListener = paramOnScrollChangeListener;
    }

    @Override
    public void setWebViewClient(WebViewClient paramWebViewClient) {
        if (!(paramWebViewClient instanceof WebViewClient))
            throw new IllegalArgumentException("WebViewClient should be instance of EmbeddedWebView$WebViewClient");
        super.setWebViewClient(paramWebViewClient);
    }

    @Override
    public boolean startNestedScroll(int paramInt) {
        return this.mChildHelper.startNestedScroll(paramInt);
    }

    @Override
    protected void onDetachedFromWindow() {
        this.mChildHelper.onDetachedFromWindow();
        super.onDetachedFromWindow();
    }

    @Override
    public void stopNestedScroll() {
        this.mChildHelper.stopNestedScroll();
    }

    public static interface OnScrollChangeListener {

        public abstract void onScrollChanged(int paramInt1, int paramInt2, int paramInt3, int paramInt4, ScrollStateChangedListener.ScrollState parama);
    }
}

18 Source : WebAppClient.java
with Apache License 2.0
from Freelander

/**
 * Created by Jun on 2016/5/8.
 */
public clreplaced WebAppClient extends WebViewClient {

    protected final static String PLATFORM = "Android";

    private Context context;

    private MultiStateView multiStateView;

    private WebView contentView;

    private WebSettings settings;

    public WebAppClient(Context context, MultiStateView multiStateView, WebView contentView) {
        this.context = context;
        this.multiStateView = multiStateView;
        this.contentView = contentView;
        initSetting();
    }

    private void initSetting() {
        settings = contentView.getSettings();
        // settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        settings.setJavaScriptEnabled(true);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        Uri uri = Uri.parse(url);
        if (uri.getHost().contains(Constants.PHPHUB_HOST)) {
            HashMap<String, String> segments = new HashMap<>();
            String key = null;
            for (String segment : uri.getPathSegments()) {
                if (key == null) {
                    key = segment;
                } else {
                    segments.put(key, segment);
                    key = null;
                }
            }
            if (segments.size() > 0) {
                if (segments.containsKey(Constants.PHPHUB_TOPIC_PATH) && !TextUtils.isEmpty(segments.get(Constants.PHPHUB_TOPIC_PATH))) {
                    url = String.format("%s%s?id=%s", Constants.DEEP_LINK_PREFIX, Constants.PHPHUB_TOPIC_PATH, segments.get(Constants.PHPHUB_TOPIC_PATH));
                } else if (segments.containsKey(Constants.PHPHUB_USER_PATH) && !TextUtils.isEmpty(segments.get(Constants.PHPHUB_USER_PATH))) {
                    url = String.format("%s%s?id=%s", Constants.DEEP_LINK_PREFIX, Constants.PHPHUB_USER_PATH, segments.get(Constants.PHPHUB_USER_PATH));
                }
            }
        }
        if (url.contains(Constants.DEEP_LINK_PREFIX)) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            if (intent.resolveActivity(context.getPackageManager()) != null) {
                context.startActivity(intent);
            } else {
                context.startActivity(Intent.createChooser(intent, "请选择浏览器"));
            }
        } else {
        // Intent intentToLaunch = WebViewPageActivity.getCallingIntent(context, webUrl);
        // context.startActivity(intentToLaunch);
        // navigator.navigateToWebView(context, url);
        }
        return true;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        if (multiStateView != null) {
            multiStateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
        }
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        if (multiStateView != null) {
            multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
        }
        addImageClickEvent();
    }

    private void addImageClickEvent() {
        LocalifyModule localify = new LocalifyClient.Builder().withreplacedetManager(context.getreplacedets()).build().localify();
        localify.rx().loadreplacedetsFile("js/ImageClickEvent.js").subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).filter(new Func1<String, Boolean>() {

            @Override
            public Boolean call(String javascript) {
                return !TextUtils.isEmpty(javascript);
            }
        }).subscribe(new Action1<String>() {

            @Override
            public void call(String javascript) {
                contentView.loadUrl(javascript.replace("{platform}", PLATFORM));
            }
        }, new Action1<Throwable>() {

            @Override
            public void call(Throwable throwable) {
                Logger.e(throwable.toString());
            }
        });
    }
}

18 Source : FeedbackActivity.java
with Apache License 2.0
from fengyuecanzhu

@SuppressLint("SetJavaScriptEnabled")
@Override
protected void initWidget() {
    super.initWidget();
    // 声明WebSettings子类
    WebSettings webSettings = binding.wvFeedback.getSettings();
    // 如果访问的页面中要与Javascript交互,则webview必须设置支持Javascript
    webSettings.setJavaScriptEnabled(true);
    binding.wvFeedback.loadUrl("https://www.wjx.cn/jq/102348283.aspx");
    binding.wvFeedback.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!url.endsWith("102348283.aspx")) {
                System.out.println(url);
                if (url.contains("complete")) {
                    DialogCreator.createCommonDialog(FeedbackActivity.this, "意见反馈", "提交成功,感谢您的建议反馈!", false, "知道了", (dialog, which) -> finish());
                }
                return true;
            }
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            if (!App.isDestroy(FeedbackActivity.this))
                binding.refreshLayout.showError();
        }
    });
    binding.wvFeedback.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100 && !App.isDestroy(FeedbackActivity.this)) {
                binding.refreshLayout.showFinish();
            }
        }
    });
}

18 Source : Forecast.java
with GNU General Public License v3.0
from evilbunny2008

private void loadWebView() {
    if (common.GetBoolPref("radarforecast", true))
        return;
    swipeLayout.setRefreshing(true);
    if (common.GetStringPref("radtype", "image").equals("image")) {
        String radar = common.context.getFilesDir() + "/radar.gif";
        File rf = new File(radar);
        if (!rf.exists() && !common.GetStringPref("RADAR_URL", "").equals("") && common.checkConnection()) {
            reloadWebView(true);
            return;
        }
        if (!rf.exists() || common.GetStringPref("RADAR_URL", "").equals("")) {
            String html = "<html>";
            if (dark_theme)
                html += "<head><style>body{color: #fff; background-color: #000;}</style></head>";
            html += "<body>Radar URL not set or is still downloading. You can go to settings to change.</body></html>";
            wv1.loadDataWithBaseURL("file:///android_res/drawable/", html, "text/html", "utf-8", null);
            swipeLayout.setRefreshing(false);
            return;
        }
        int height = Math.round((float) Resources.getSystem().getDisplayMetrics().widthPixels / Resources.getSystem().getDisplayMetrics().scaledDensity * 0.955f);
        int width = Math.round((float) Resources.getSystem().getDisplayMetrics().heightPixels / Resources.getSystem().getDisplayMetrics().scaledDensity * 0.955f);
        String html = "<!DOCTYPE html>\n" + "<html>\n" + "  <head>\n" + "    <meta charset='utf-8'>\n" + "    <meta name='viewport' content='width=device-width, initial-scale=1.0'>\n";
        if (dark_theme)
            html += "<style>body{color: #fff; background-color: #000;}</style>";
        html += "  </head>\n" + "  <body>\n" + "\t<div style='text-align:center;'>\n" + "\t<img style='margin:0px;padding:0px;border:0px;text-align:center;max-height:" + height + "px;max-width:" + width + "px;width:auto;height:auto;'\n" + "\tsrc='file://" + radar + "'>\n" + "\t</div>\n" + "  </body>\n" + "</html>";
        wv1.loadDataWithBaseURL("file:///android_res/drawable/", html, "text/html", "utf-8", null);
        rl.setVisibility(View.VISIBLE);
        wv2.setVisibility(View.GONE);
        swipeLayout.setRefreshing(false);
    } else if (common.GetStringPref("radtype", "image").equals("webpage") && !common.GetStringPref("RADAR_URL", "").equals("")) {
        rl.setVisibility(View.GONE);
        wv2.setVisibility(View.VISIBLE);
        if (common.checkConnection()) {
            wv2.clearCache(true);
            wv2.clearHistory();
            wv2.clearFormData();
            WebSettings webSettings = wv2.getSettings();
            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        }
        wv2.loadUrl(common.GetStringPref("RADAR_URL", ""));
        swipeLayout.setRefreshing(false);
    }
    swipeLayout.setRefreshing(false);
}

18 Source : EasyBridgeWebView.java
with MIT License
from easilycoder

@SuppressLint({ "SetJavaScriptEnabled", "AddJavascriptInterface" })
private void initWebView() {
    // 开启JavaScript的支持
    WebSettings webSettings = getSettings();
    if (webSettings != null) {
        webSettings.setJavaScriptEnabled(true);
    }
    addJavascriptInterface(easyBridge, MAPPING_JS_INTERFACE_NAME);
    EasyBridgeWebChromeClient webChromeClient = new EasyBridgeWebChromeClient(this);
    setWebChromeClient(webChromeClient);
    // register a default handler to subscribe the event of bridge injected
    registerHandler(new BaseBridgeHandler(REGISTER_INJECT_FINISHED, this) {

        @Override
        public void onCall(String parameters, ResultCallBack callBack) {
            Logger.debug("inject bridge success in page:" + getUrl());
            if (listener != null) {
                listener.onInjected();
            }
            setInjected(true);
        }
    });
}

18 Source : RexxarWebViewCore.java
with MIT License
from douban

private void setup() {
    setBackgroundColor(Color.WHITE);
    WebSettings ws = getSettings();
    setupWebSettings(ws);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        setWebContentsDebuggingEnabled(Rexxar.DEBUG);
    }
    if (null == mWebViewClient) {
        mWebViewClient = new RexxarWebViewClient();
    }
    setWebViewClient(mWebViewClient);
    if (null == mWebChromeClient) {
        mWebChromeClient = new RexxarWebChromeClient();
    }
    setWebChromeClient(mWebChromeClient);
    setDownloadListener(getDownloadListener());
}

18 Source : HelpActivity.java
with GNU General Public License v3.0
from dftec-es

private void setTextSize() {
    WebSettings webSettings = mHelpView.getSettings();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    int textSize = SettingsActivity.getNumericPref(prefs, SettingsActivity.KEY_TEXT_SIZE, SettingsActivity.DEF_TEXT_SIZE);
    if (textSize >= 16) {
        webSettings.setDefaultFontSize(16 + FONT_OFFSET);
    } else if (textSize >= 14) {
        webSettings.setDefaultFontSize(14 + FONT_OFFSET);
    } else if (textSize >= 12) {
        webSettings.setDefaultFontSize(12 + FONT_OFFSET);
    } else if (textSize >= 10) {
        webSettings.setDefaultFontSize(10 + FONT_OFFSET);
    } else if (textSize >= 8) {
        webSettings.setDefaultFontSize(8 + FONT_OFFSET);
    } else {
        webSettings.setDefaultFontSize(16);
    }
}

18 Source : VideoActivity.java
with Apache License 2.0
from CrazyDudo

/**
 * Created by cd on 2018/7/19.
 */
public clreplaced VideoActivity extends AppCompatActivity implements VideoContract.View {

    private static final String TAG = "VideoActivity";

    private WebView webView;

    // default url
    private String url = "https://v.qq.com/";

    private List<PlaylistBean.PlatformlistBean> mLeftListData = new ArrayList<>();

    private List<PlaylistBean.ListBean> mRightListData = new ArrayList<>();

    private String platformVideoUrl = "";

    private WebSettings webSetting;

    private DrawerLayout drawerLayout;

    private ListView lvLeft;

    private ListView lvRight;

    private PlatformListAdapter mAdapter;

    private ChannelListAdapter channelListAdapter;

    private String furl;

    private ProgressBar progressBar;

    private VideoContract.Presenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new VideoPresenter(this);
        presenter.requestVideoResource();
        initView();
    }

    private void initView() {
        progressBar = findViewById(R.id.progressbar);
        drawerLayout = findViewById(R.id.dl_layout);
        webView = findViewById(R.id.webview);
        lvLeft = findViewById(R.id.lv_left);
        lvRight = findViewById(R.id.lv_right);
        drawerLayout = findViewById(R.id.dl_layout);
        initWebView();
    }

    private void initLeftMenu(final List<PlaylistBean.PlatformlistBean> mListData) {
        mAdapter = new PlatformListAdapter(VideoActivity.this, R.layout.platform_list_item, mListData);
        lvLeft.setDivider(null);
        lvLeft.setAdapter(mAdapter);
        lvLeft.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (drawerLayout.isDrawerOpen(Gravity.LEFT)) {
                    // 如果此时抽屉窗口打开,就给他关闭
                    drawerLayout.closeDrawer(Gravity.LEFT);
                }
                loadUrl(mListData.get(position).getUrl());
                Toast.makeText(VideoActivity.this, mListData.get(position).getName(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initRightMenu(final List<PlaylistBean.ListBean> mListData) {
        channelListAdapter = new ChannelListAdapter(VideoActivity.this, R.layout.platform_list_item, mListData);
        lvRight.setDivider(null);
        lvRight.setAdapter(channelListAdapter);
        lvRight.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
                    // 如果此时抽屉窗口打开,就给他关闭
                    drawerLayout.closeDrawer(Gravity.RIGHT);
                }
                if (StringUtil.getCount(platformVideoUrl, "http") > 1) {
                    platformVideoUrl = platformVideoUrl.substring(platformVideoUrl.indexOf("=") + 1);
                }
                playVIP(mListData.get(position).getUrl(), platformVideoUrl);
                Toast.makeText(VideoActivity.this, mListData.get(position).getName(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.ECLAIR_MR1)
    private void initWebView() {
        webSetting = webView.getSettings();
        webSetting.setDefaultTextEncodingName("utf-8");
        // 必须保留
        webSetting.setJavaScriptEnabled(true);
        // 保留,否则无法播放优酷视频网页
        webSetting.setDomStorageEnabled(true);
        // 重写一下
        webView.setWebChromeClient(new MyWebChromeClient());
        webView.setWebViewClient(new MyWebViewClient());
        loadUrl(url);
    }

    private void loadUrl(String url) {
        webView.loadUrl(url);
        Log.d(TAG, "loadUrl: " + url);
    }

    private void playVIP(String channelUrl, String url) {
        furl = channelUrl + url;
        loadUrl(furl);
        Log.d(TAG, "playVIP====" + furl);
    }

    @Override
    public void onLoadSuccess(PlaylistBean playlistBean) {
        mLeftListData = playlistBean.getPlatformlist();
        mRightListData = playlistBean.getList();
        initLeftMenu(mLeftListData);
        initRightMenu(mRightListData);
        Log.d(TAG, "onSuccess: " + mLeftListData.toString());
    }

    @Override
    public void onLoadError(String error) {
        // read from local
        Toast.makeText(this, "Loading error:" + error, Toast.LENGTH_SHORT).show();
        String fromreplacedets = getFromreplacedets("viplist_backup.json");
        Gson gson = new Gson();
        PlaylistBean playlistBean = gson.fromJson(fromreplacedets, PlaylistBean.clreplaced);
        setResData(playlistBean);
    }

    public void setResData(PlaylistBean playlistBean) {
        mLeftListData = playlistBean.getPlatformlist();
        mRightListData = playlistBean.getList();
        initLeftMenu(mLeftListData);
        initRightMenu(mRightListData);
        Toast.makeText(this, "load from local", Toast.LENGTH_SHORT).show();
    }

    /**
     * 读取replacedets文件
     * @param fileName
     * @return
     */
    public String getFromreplacedets(String fileName) {
        try {
            InputStreamReader inputReader = new InputStreamReader(getResources().getreplacedets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String Result = "";
            while ((line = bufReader.readLine()) != null) Result += line;
            return Result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void setPresenter(VideoContract.Presenter presenter) {
        this.presenter = presenter;
    }

    private clreplaced MyWebChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                // 加载完网页进度条消失
                progressBar.setVisibility(View.GONE);
            } else {
                // 开始加载网页时显示进度条
                progressBar.setVisibility(View.VISIBLE);
                // 设置进度值
                progressBar.setProgress(newProgress);
            }
        }
    }

    // 监听 所有点击的链接,如果拦截到我们需要的,就跳转到相对应的页面。
    private clreplaced MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d(TAG, "shouldOverrideUrlLoading: current page===" + url);
            platformVideoUrl = url;
            // Toast.makeText(VideoActivity.this, "shouldOverrideUrlLoading: ==" + url, Toast.LENGTH_SHORT).show();
            // 这里进行url拦截
            /*            if (url != null && url.contains("vip")) {
                Toast.makeText(VideoActivity.this, "url 拦截", Toast.LENGTH_SHORT).show();
                Toast.makeText(VideoActivity.this, "url 拦截", Toast.LENGTH_SHORT).show();
                return true;
            }
*/
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // view.getSettings().setJavaScriptEnabled(true);
            // super.onPageFinished(view, url);
            // view.loadUrl("javascript:function setTop(){doreplacedent.querySelector('.ad-footer').style.display=\"none\";}setTop();");
            // super.onPageFinished(view, url);
            view.loadUrl("javascript:doreplacedent.getElementById('imPage').style.display='none';");
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            url = url.toLowerCase();
            if (!ADFilterTool.hasAd(VideoActivity.this, url)) {
                return super.shouldInterceptRequest(view, url);
            } else {
                return new WebResourceResponse(null, null, null);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 这是一个监听用的按键的方法,keyCode 监听用户的动作,如果是按了返回键,同时Webview要返回的话,WebView执行回退操作,因为mWebView.canGoBack()返回的是一个Boolean类型,所以我们把它返回为true
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}

18 Source : EventWebView.java
with Apache License 2.0
from collegeconnect

public clreplaced EventWebView extends Fragment {

    WebView webView;

    ProgressBar progressBar;

    WebSettings webSettings;

    FloatingActionButton floatingActionButton;

    ImageView imageView;

    TextView textView, textslow;

    boolean hasConnect;

    private AdView mAdView;

    String finalUrl;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        String desired_string = arguments.getString("Url");
        if (desired_string.contains("https://"))
            finalUrl = desired_string;
        else
            finalUrl = "https://" + desired_string;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_event_web_view, container, false);
        mAdView = view.findViewById(R.id.adViewevent);
        webView = view.findViewById(R.id.eventWebView);
        progressBar = view.findViewById(R.id.eventprog);
        textView = view.findViewById(R.id.tv_errorevent);
        imageView = view.findViewById(R.id.imageVieweve);
        imageView.setVisibility(View.GONE);
        textView.setVisibility(View.GONE);
        progressBar.setVisibility(View.GONE);
        textslow = view.findViewById(R.id.texterrorevent);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getActivity() != null) {
            floatingActionButton = getActivity().findViewById(R.id.createEvent);
            TextView tv = getActivity().findViewById(R.id.tvreplacedle);
            tv.setText("Event Details");
        }
        MobileAds.initialize(getContext());
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
        ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
                if (capabilities != null) {
                    if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                        hasConnect = true;
                    } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                        hasConnect = true;
                    } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
                        hasConnect = true;
                    }
                }
            } else {
                try {
                    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
                    if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
                        hasConnect = true;
                    }
                } catch (Exception e) {
                    Log.i("update_status", "" + e.getMessage());
                }
            }
        }
        textslow.setVisibility(View.GONE);
        if (hasConnect) {
            // progressBar.postDelayed(new Runnable() {
            // @Override
            // public void run() {
            // progressBar.setVisibility(View.GONE);
            // }
            // }, 500);
            // show the webview
            webView.setWebViewClient(new WebViewClient() {

                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);
                    progressBar.setVisibility(View.VISIBLE);
                // textslow.postDelayed(new Runnable() {
                // @Override
                // public void run() {
                // textslow.setVisibility(View.VISIBLE);
                // }
                // },3500);
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    progressBar.setVisibility(View.GONE);
                    textslow.setVisibility(View.GONE);
                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                    Uri uri = request.getUrl();
                    if (uri.toString().startsWith("intent://")) {
                        Intent intent = null;
                        try {
                            intent = Intent.parseUri(uri.toString(), Intent.URI_INTENT_SCHEME);
                        } catch (URISyntaxException e) {
                            e.printStackTrace();
                        }
                        if (intent != null) {
                            String fallbackurl = intent.getStringExtra("browser_fallback_url");
                            if (fallbackurl != null) {
                                webView.loadUrl(fallbackurl);
                                return true;
                            } else
                                return false;
                        }
                    }
                    return super.shouldOverrideUrlLoading(view, request);
                }
            });
            webView.loadUrl(finalUrl);
            webSettings = webView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setDomStorageEnabled(true);
            webView.canGoBack();
            webView.setOnKeyListener(new View.OnKeyListener() {

                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == MotionEvent.ACTION_UP && webView.canGoBack()) {
                        webView.goBack();
                        return true;
                    }
                    return false;
                }
            });
        } else {
            // do what ever you need when when no internet connection
            progressBar.setVisibility(View.GONE);
            webView.setVisibility(View.GONE);
            textView.setVisibility(View.VISIBLE);
            imageView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        ((AppCompatActivity) getActivity()).getSupportActionBar().show();
        floatingActionButton.setVisibility(View.VISIBLE);
    }

    @Override
    public void onStart() {
        super.onStart();
        floatingActionButton.setVisibility(View.INVISIBLE);
    }
}

18 Source : JSWebView.java
with GNU General Public License v3.0
from Cocos-BCX

@SuppressLint({ "SetJavaScriptEnabled", "ObsoleteSdkInt" })
private void initialize() {
    progressView = new ProgressView(context);
    progressView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Utils.dip2px(2)));
    progressView.setColor(getResources().getColor(R.color.color_262A33));
    progressView.setProgress(10);
    addView(progressView);
    WebSettings settings = getSettings();
    initializeSettings(settings);
    setWebChromeClient(new JsWebChromeClient());
}

18 Source : PopupBridgeClientUnitTest.java
with MIT License
from braintree

@Test
public void constructor_enablesJavascriptOnWebView() {
    WebSettings webSettings = mock(WebSettings.clreplaced);
    when(webView.getSettings()).thenReturn(webSettings);
    new PopupBridgeClient(activityRef, webViewRef, "my-custom-url-scheme", browserSwitchClient);
    verify(webSettings).setJavaScriptEnabled(eq(true));
}

18 Source : WebViewJavascriptEnabledActivity.java
with GNU Lesser General Public License v3.0
from blackarbiter

private void disableJavaScriptEnabled(WebSettings webSettings) {
    // Should not rise an alert
    webSettings.setJavaScriptEnabled(false);
}

18 Source : CacheableWebView.java
with Apache License 2.0
from bkhezry

@SuppressLint("SetJavaScriptEnabled")
private void setLoadSettings() {
    WebSettings webSettings = getSettings();
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setUseWideViewPort(true);
    webSettings.setJavaScriptEnabled(true);
}

18 Source : CacheableWebView.java
with Apache License 2.0
from bkhezry

private void enableCache() {
    WebSettings webSettings = getSettings();
    webSettings.setAppCacheEnabled(true);
    webSettings.setAllowFileAccess(true);
    webSettings.setAppCachePath(getContext().getApplicationContext().getCacheDir().getAbsolutePath());
}

18 Source : MainActivity.java
with MIT License
from bituniverse

private void loadWebView(WebView webView, int size, String encryptText) {
    String htmlShareAccountName = "<html><head><style>body,html { margin:0; padding:0; text-align:center;}</style><meta name=viewport content=width=" + size + ",user-scalable=no/></head><body><canvas width=" + size + " height=" + size + " data-jdenticon-hash=" + encryptText + "></canvas><script src=https://cdn.jsdelivr.net/jdenticon/1.3.2/jdenticon.min.js async></script></body></html>";
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webView.loadData(htmlShareAccountName, "text/html", "UTF-8");
}

18 Source : WebViewActivity.java
with GNU General Public License v3.0
from Bakumon

public void initWebView() {
    WebSettings settings = mWebView.getSettings();
    settings.setLoadWithOverviewMode(true);
    settings.setJavaScriptEnabled(true);
    settings.setAppCacheEnabled(true);
    settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    settings.setSupportZoom(true);
    mWebView.setWebChromeClient(new MyWebChrome());
    mWebView.setWebViewClient(new MyWebClient());
    mWebView.setOnScrollChangedCallback(new ObservableWebView.OnScrollChangedCallback() {

        @Override
        public void onScroll(int dx, int dy) {
            if (dy > 0) {
                mFloatingActionButton.hide();
            } else {
                mFloatingActionButton.show();
            }
        }
    });
}

18 Source : FastWebActivity.java
with Apache License 2.0
from AriesHoo

protected void initAgentWeb() {
    mAgentBuilder = AgentWeb.with(this).setAgentWebParent(mContainer, new ViewGroup.LayoutParams(-1, -1)).useDefaultIndicator(getProgressColor() != -1 ? getProgressColor() : ContextCompat.getColor(mContext, R.color.colorreplacedleText), getProgressHeight()).useMiddlewareWebChrome(new MiddlewareWebChromeBase() {

        @Override
        public void onReceivedreplacedle(WebView view, String replacedle) {
            super.onReceivedreplacedle(view, replacedle);
            mCurrentUrl = view.getUrl();
            mreplacedleBar.setreplacedleMainText(replacedle);
        }
    }).setSecurityType(AgentWeb.SecurityType.STRICT_CHECK);
    setAgentWeb(mAgentBuilder);
    mAgentWeb = mAgentBuilder.createAgentWeb().ready().go(mUrl);
    WebSettings webSettings = mAgentWeb.getAgentWebSettings().getWebSettings();
    // 设置webView自适应屏幕
    webSettings.setUseWideViewPort(true);
    webSettings.setLoadWithOverviewMode(true);
    setAgentWeb(mAgentWeb);
}

18 Source : WebSettingsCompat.java
with Apache License 2.0
from androidx

/**
 * Gets whether Safe Browsing is enabled.
 * See {@link #setSafeBrowsingEnabled}.
 *
 * <p>
 * This method should only be called if
 * {@link WebViewFeature#isFeatureSupported(String)}
 * returns true for {@link WebViewFeature#SAFE_BROWSING_ENABLE}.
 *
 * @return {@code true} if Safe Browsing is enabled and {@code false} otherwise.
 */
@SuppressLint("NewApi")
@RequiresFeature(name = WebViewFeature.SAFE_BROWSING_ENABLE, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
public static boolean getSafeBrowsingEnabled(@NonNull WebSettings settings) {
    WebViewFeatureInternal feature = WebViewFeatureInternal.SAFE_BROWSING_ENABLE;
    if (feature.isSupportedByFramework()) {
        return settings.getSafeBrowsingEnabled();
    } else if (feature.isSupportedByWebView()) {
        return getAdapter(settings).getSafeBrowsingEnabled();
    } else {
        throw WebViewFeatureInternal.getUnsupportedOperationException();
    }
}

18 Source : WebSettingsCompat.java
with Apache License 2.0
from androidx

/**
 * Sets whether the WebView’s internal error page should be suppressed or displayed
 * for bad navigations. True means suppressed (not shown), false means it will be
 * displayed.
 * The default value is false.
 *
 * <p>
 * This method should only be called if
 * {@link WebViewFeature#isFeatureSupported(String)}
 * returns true for {@link WebViewFeature#SUPPRESS_ERROR_PAGE}.
 *
 * @param suppressed whether the WebView should suppress its internal error page
 *
 * TODO(cricke): unhide
 * @hide
 */
@RestrictTo(RestrictTo.Scope.LIBRARY)
@SuppressLint("NewApi")
@RequiresFeature(name = WebViewFeature.SUPPRESS_ERROR_PAGE, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
public static void setWillSuppressErrorPage(@NonNull WebSettings settings, boolean suppressed) {
    WebViewFeatureInternal feature = WebViewFeatureInternal.SUPPRESS_ERROR_PAGE;
    if (feature.isSupportedByWebView()) {
        getAdapter(settings).setWillSuppressErrorPage(suppressed);
    } else {
        throw WebViewFeatureInternal.getUnsupportedOperationException();
    }
}

18 Source : WebSettingsCompat.java
with Apache License 2.0
from androidx

/**
 * Sets whether Safe Browsing is enabled. Safe Browsing allows WebView to
 * protect against malware and phishing attacks by verifying the links.
 *
 * <p>
 * Safe Browsing can be disabled for all WebViews using a manifest tag (read <a
 * href="{@docRoot}reference/android/webkit/WebView.html">general Safe Browsing info</a>). The
 * manifest tag has a lower precedence than this API.
 *
 * <p>
 * Safe Browsing is enabled by default for devices which support it.
 *
 * <p>
 * This method should only be called if
 * {@link WebViewFeature#isFeatureSupported(String)}
 * returns true for {@link WebViewFeature#SAFE_BROWSING_ENABLE}.
 *
 * @param enabled Whether Safe Browsing is enabled.
 */
@SuppressLint("NewApi")
@RequiresFeature(name = WebViewFeature.SAFE_BROWSING_ENABLE, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
public static void setSafeBrowsingEnabled(@NonNull WebSettings settings, boolean enabled) {
    WebViewFeatureInternal feature = WebViewFeatureInternal.SAFE_BROWSING_ENABLE;
    if (feature.isSupportedByFramework()) {
        settings.setSafeBrowsingEnabled(enabled);
    } else if (feature.isSupportedByWebView()) {
        getAdapter(settings).setSafeBrowsingEnabled(enabled);
    } else {
        throw WebViewFeatureInternal.getUnsupportedOperationException();
    }
}

18 Source : WebSettingsCompat.java
with Apache License 2.0
from androidx

/**
 * Gets whether the WebView’s internal error page will be suppressed or displayed
 *
 * <p>
 * This method should only be called if
 * {@link WebViewFeature#isFeatureSupported(String)}
 * returns true for {@link WebViewFeature#SUPPRESS_ERROR_PAGE}.
 *
 * @return true if the WebView will suppress its internal error page
 * @see #setWillSuppressErrorPage
 *
 * TODO(cricke): unhide
 * @hide
 */
@RestrictTo(RestrictTo.Scope.LIBRARY)
@SuppressLint("NewApi")
@RequiresFeature(name = WebViewFeature.SUPPRESS_ERROR_PAGE, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
public static boolean willSuppressErrorPage(@NonNull WebSettings settings) {
    WebViewFeatureInternal feature = WebViewFeatureInternal.SUPPRESS_ERROR_PAGE;
    if (feature.isSupportedByWebView()) {
        return getAdapter(settings).willSuppressErrorPage();
    } else {
        throw WebViewFeatureInternal.getUnsupportedOperationException();
    }
}

18 Source : WebSettingsCompat.java
with Apache License 2.0
from androidx

/**
 * Gets whether this WebView should raster tiles when it is
 * offscreen but attached to a window.
 *
 * <p>
 * This method should only be called if
 * {@link WebViewFeature#isFeatureSupported(String)}
 * returns true for {@link WebViewFeature#OFF_SCREEN_PRERASTER}.
 *
 * @return {@code true} if this WebView will raster tiles when it is
 * offscreen but attached to a window.
 */
@SuppressLint("NewApi")
@RequiresFeature(name = WebViewFeature.OFF_SCREEN_PRERASTER, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
public static boolean getOffscreenPreRaster(@NonNull WebSettings settings) {
    WebViewFeatureInternal feature = WebViewFeatureInternal.OFF_SCREEN_PRERASTER;
    if (feature.isSupportedByFramework()) {
        return settings.getOffscreenPreRaster();
    } else if (feature.isSupportedByWebView()) {
        return getAdapter(settings).getOffscreenPreRaster();
    } else {
        throw WebViewFeatureInternal.getUnsupportedOperationException();
    }
}

18 Source : WebSettingsCompat.java
with Apache License 2.0
from androidx

/**
 * Set the force dark mode for this WebView.
 *
 * <p>
 * This method should only be called if
 * {@link WebViewFeature#isFeatureSupported(String)}
 * returns true for {@link WebViewFeature#FORCE_DARK}.
 *
 * <p>
 * If equals to {@link ForceDark#FORCE_DARK_ON} then {@link #setForceDarkStrategy} is used to
 * specify darkening strategy.
 *
 * @param forceDarkMode the force dark mode to set.
 * @see #getForceDark
 */
@SuppressLint("NewApi")
@RequiresFeature(name = WebViewFeature.FORCE_DARK, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
public static void setForceDark(@NonNull WebSettings settings, @ForceDark int forceDarkMode) {
    WebViewFeatureInternal feature = WebViewFeatureInternal.FORCE_DARK;
    if (feature.isSupportedByFramework()) {
        settings.setForceDark(forceDarkMode);
    } else if (feature.isSupportedByWebView()) {
        getAdapter(settings).setForceDark(forceDarkMode);
    } else {
        throw WebViewFeatureInternal.getUnsupportedOperationException();
    }
}

18 Source : WebSettingsCompat.java
with Apache License 2.0
from androidx

/**
 * Get how content is darkened for this WebView.
 *
 * <p>
 * The default force dark strategy is
 * {@link #DARK_STRATEGY_PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING}
 *
 * <p>
 * This method should only be called if
 * {@link WebViewFeature#isFeatureSupported(String)}
 * returns true for {@link WebViewFeature#FORCE_DARK_STRATEGY}.
 *
 * @return the currently set force dark strategy.
 * @see #setForceDarkStrategy
 */
@SuppressLint("NewApi")
@RequiresFeature(name = WebViewFeature.FORCE_DARK_STRATEGY, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
@ForceDarkStrategy
public static int getForceDarkStrategy(@NonNull WebSettings settings) {
    WebViewFeatureInternal feature = WebViewFeatureInternal.FORCE_DARK_STRATEGY;
    if (feature.isSupportedByWebView()) {
        return getAdapter(settings).getForceDark();
    } else {
        throw WebViewFeatureInternal.getUnsupportedOperationException();
    }
}

18 Source : WebSettingsCompat.java
with Apache License 2.0
from androidx

/**
 * Sets whether this WebView should raster tiles when it is
 * offscreen but attached to a window. Turning this on can avoid
 * rendering artifacts when animating an offscreen WebView on-screen.
 * Offscreen WebViews in this mode use more memory. The default value is
 * false.<br>
 * Please follow these guidelines to limit memory usage:
 * <ul>
 * <li> WebView size should be not be larger than the device screen size.
 * <li> Limit use of this mode to a small number of WebViews. Use it for
 *   visible WebViews and WebViews about to be animated to visible.
 * </ul>
 *
 * <p>
 * This method should only be called if
 * {@link WebViewFeature#isFeatureSupported(String)}
 * returns true for {@link WebViewFeature#OFF_SCREEN_PRERASTER}.
 */
@SuppressLint("NewApi")
@RequiresFeature(name = WebViewFeature.OFF_SCREEN_PRERASTER, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
public static void setOffscreenPreRaster(@NonNull WebSettings settings, boolean enabled) {
    WebViewFeatureInternal feature = WebViewFeatureInternal.OFF_SCREEN_PRERASTER;
    if (feature.isSupportedByFramework()) {
        settings.setOffscreenPreRaster(enabled);
    } else if (feature.isSupportedByWebView()) {
        getAdapter(settings).setOffscreenPreRaster(enabled);
    } else {
        throw WebViewFeatureInternal.getUnsupportedOperationException();
    }
}

18 Source : WebSettingsCompat.java
with Apache License 2.0
from androidx

/**
 * Set how WebView content should be darkened.
 *
 * <p>
 * This method should only be called if
 * {@link WebViewFeature#isFeatureSupported(String)}
 * returns true for {@link WebViewFeature#FORCE_DARK_STRATEGY}.
 *
 * <p>
 * The specified strategy is only used if force dark mode is on.
 * See {@link #setForceDark}.
 *
 * @param forceDarkBehavior the force dark strategy to set.
 * @see #getForceDarkStrategy
 */
@SuppressLint("NewApi")
@RequiresFeature(name = WebViewFeature.FORCE_DARK_STRATEGY, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
public static void setForceDarkStrategy(@NonNull WebSettings settings, @ForceDarkStrategy int forceDarkBehavior) {
    WebViewFeatureInternal feature = WebViewFeatureInternal.FORCE_DARK_STRATEGY;
    if (feature.isSupportedByWebView()) {
        getAdapter(settings).setForceDarkStrategy(forceDarkBehavior);
    } else {
        throw WebViewFeatureInternal.getUnsupportedOperationException();
    }
}

See More Examples