Example usage for android.webkit WebSettings setAppCacheEnabled

List of usage examples for android.webkit WebSettings setAppCacheEnabled

Introduction

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

Prototype

public abstract void setAppCacheEnabled(boolean flag);

Source Link

Document

Sets whether the Application Caches API should be enabled.

Usage

From source file:com.usabusi.newsreader.ArticleFragment.java

/**
 * Sets up the UI. It consists if a single WebView.
 *//*from   www.j a  va 2  s.co  m*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mWebView = new WebView(getActivity());
    //http://stackoverflow.com/questions/17259537/load-webview-from-cache
    WebSettings webSettings = mWebView.getSettings();
    // Enable JavaScript
    webSettings.setJavaScriptEnabled(true); // enable javascript
    mWebView.setHorizontalScrollBarEnabled(false);
    webSettings.setAppCacheMaxSize(5 * 1024 * 1024); // 5MB
    webSettings.setAppCachePath(getActivity().getApplicationContext().getCacheDir().getAbsolutePath());
    webSettings.setAllowFileAccess(true);
    webSettings.setAppCacheEnabled(true);
    webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); // load online by default
    //http://stackoverflow.com/questions/25161720/url-opened-in-browser-instead-of-web-view
    mWebView.setVisibility(View.VISIBLE);
    webSettings.setPluginState(WebSettings.PluginState.ON);
    webSettings.setBuiltInZoomControls(true);

    //final Activity activity = this;
    // Make WebClient
    mWebView.setWebViewClient(new WebViewClient() {
        // Trace Errors
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Toast.makeText(getActivity().getApplicationContext(), description, Toast.LENGTH_SHORT).show();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //http://developer.android.com/guide/webapps/webview.html#HandlingNavigation
            //                view.loadUrl(url);
            //                return true;
            return false;
        }
    });

    loadWebView();
    return mWebView;
}

From source file:com.chatwingsdk.fragments.CommunicationMessagesFragment.java

private void setupWebView() {
    mWebview.setWebViewClient(new WebViewClient() {
        @Override/*  w w  w  . jav a2 s . c om*/
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            try {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } catch (Exception e) {
                return false;
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            //TODO should be when page start rendering chatbox
            LogUtils.v("Loading page DONE");
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            LogUtils.v("Loading page Oh no! " + description);
        }
    });

    mWebview.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            LogUtils.v("Loading page " + newProgress + ":" + mWebview);
        }
    });
    WebSettings webSettings = mWebview.getSettings();
    webSettings.setAppCacheEnabled(false);
    webSettings.setJavaScriptEnabled(true);
    mWebview.addJavascriptInterface(mFayeJsInterface, ChatWingJSInterface.CHATWING_JS_NAME);
}

From source file:com.github.snowdream.android.app.books.BookFragment.java

private void initUI(View rootview) {
    webView = (WebView) rootview.findViewById(R.id.webView);
    //        progressbar = (SmoothProgressBar) rootview.findViewById(R.id.progressbar);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setAllowFileAccess(true);
    webSettings.setSupportZoom(true);/*from   w  w w.  jav a2s . c  om*/
    webSettings.setBuiltInZoomControls(true);
    webSettings.setUseWideViewPort(true);
    String appCachePath = getActivity().getApplicationContext().getCacheDir().getAbsolutePath();
    webSettings.setAppCachePath(appCachePath);
    webSettings.setAppCacheEnabled(true);

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            //                progressbar.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            //                progressbar.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            //                progressbar.setVisibility(View.INVISIBLE);
        }
    });
    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }
    });

    // The "loadAdOnCreate" and "testDevices" XML attributes no longer available.
    AdView adView = (AdView) rootview.findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .addTestDevice(TEST_DEVICE_ID).build();
    adView.loadAd(adRequest);

    getView().setFocusableInTouchMode(true);
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (webView.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK) {
                webView.goBack();

                return true;
            }
            return false;
        }
    });
}

From source file:org.openqa.selendroid.server.model.SelendroidWebDriver.java

private void configureWebView(final WebView view) {
    ServerInstrumentation.getInstance().runOnUiThread(new Runnable() {

        @Override//from  w ww.  j a v a  2 s.  c o m
        public void run() {
            view.clearCache(true);
            view.clearFormData();
            view.clearHistory();
            view.setFocusable(true);
            view.setFocusableInTouchMode(true);
            view.setNetworkAvailable(true);
            view.setWebChromeClient(new MyWebChromeClient());

            WebSettings settings = view.getSettings();
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setSupportMultipleWindows(true);
            settings.setBuiltInZoomControls(true);
            settings.setJavaScriptEnabled(true);
            settings.setAppCacheEnabled(true);
            settings.setAppCacheMaxSize(10 * 1024 * 1024);
            settings.setAppCachePath("");
            settings.setDatabaseEnabled(true);
            settings.setDomStorageEnabled(true);
            settings.setGeolocationEnabled(true);
            settings.setSaveFormData(false);
            settings.setSavePassword(false);
            settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
            // Flash settings
            settings.setPluginState(WebSettings.PluginState.ON);

            // Geo location settings
            settings.setGeolocationEnabled(true);
            settings.setGeolocationDatabasePath("/data/data/selendroid");
        }
    });
}

From source file:com.wpi.assistments.HomeTabbedActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_webview);

    final ProgressDialog pd = ProgressDialog.show(this, "", "Loading...", true);

    isTeacher = false;/*from w  ww.j a  v  a 2s.  c  om*/
    toggle = true;
    logoutFlag = false;

    homeWebView = (WebView) findViewById(R.id.homeWebView);
    homeWebView.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
            Log.i("test", view.getUrl());
            if (view.getUrl().equals("https://www.assistments.org/account/login") && !logoutFlag) {

                Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                intent.putExtra("showPopup", "true");
                startActivity(intent);
                finish();
            } else if (view.getUrl().equals("https://www.assistments.org/teacher")) {
                isTeacher = true;
            } else if (view.getUrl().equals("https://www.assistments.org/account/login") && logoutFlag) {
                Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(intent);
            }

            if (!homeWebView.canGoBack()) {
                btnBack.setEnabled(false);
            } else {
                btnBack.setEnabled(true);
            }

            if (!homeWebView.canGoForward()) {
                btnForward.setEnabled(false);
            } else {
                btnForward.setEnabled(true);
            }

            if (pd.isShowing() && pd != null) {
                pd.dismiss();
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            pd.show();
            view.loadUrl(url);
            return true;
        }
    });
    homeWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
            new AlertDialog.Builder(webviewContext).setTitle("ASSISTments").setMessage(message)
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            logoutFlag = true;
                            result.confirm();
                        }
                    }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            result.cancel();
                        }
                    }).create().show();

            return true;
        }
    });

    if (savedInstanceState != null) {
        homeWebView.restoreState(savedInstanceState);
    } else {
        /** Scaling, replaced by overview mode and wide view port
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        if (size.x <= 780) {
           int scaleRate = (int) ((size.x) / 7.8);
           Log.i("test", Integer.toString(size.x));
           homeWebView.setInitialScale(scaleRate);
        }
        */

        Intent intent = getIntent();

        if (intent.getStringExtra("username").equals("") && intent.getStringExtra("password").equals("")) {
            homeWebView.loadUrl("https://www.assistments.org/signup");

        } else {
            String username = intent.getStringExtra("username");
            String password = intent.getStringExtra("password");

            String postData = "login=" + username + "&password=" + password + "&commit=Log in";
            homeWebView.postUrl("https://www.assistments.org/account/login",
                    EncodingUtils.getBytes(postData, "BASE64"));
        }

    }

    WebSettings settings = homeWebView.getSettings();
    settings.setSaveFormData(false);
    settings.setSavePassword(false);
    settings.setJavaScriptEnabled(true);
    settings.setBuiltInZoomControls(true);
    settings.setDisplayZoomControls(false);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);
    settings.setSupportMultipleWindows(true);
    settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    settings.setAppCacheEnabled(false);
    settings.setDomStorageEnabled(true);
    settings.setDatabaseEnabled(true);
    settings.setUseWideViewPort(false);
    settings.setLoadWithOverviewMode(true);
    homeWebView.clearCache(true);
    homeWebView.setPadding(0, 0, 0, 0);
    homeWebView.setInitialScale(getScale());

    btnBack = (Button) findViewById(R.id.btnBack);
    btnBack.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            homeWebView.goBack();
        }
    });

    btnRefresh = (Button) findViewById(R.id.btnRefresh);
    btnRefresh.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            //homeWebView.zoomOut();
            homeWebView.scrollTo(1000, 0);
            Log.i("test", "111");
            //homeWebView.reload();
        }
    });

    btnForward = (Button) findViewById(R.id.btnForward);
    btnForward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            homeWebView.goForward();
        }
    });

    btnOffline = (Button) findViewById(R.id.btnOffline);
    btnOffline.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (toggle) {
                homeWebView.loadUrl(
                        "https://www.assistments.org/assistments/student/index.html#offlineUserAssignmentList/");
                btnOffline.setText("Home");
                toggle = false;
            } else {
                if (isTeacher) {
                    homeWebView.loadUrl("https://www.assistments.org/teacher");
                } else {
                    homeWebView.loadUrl("https://www.assistments.org/tutor");
                }
                btnOffline.setText("Offline");
                toggle = true;
            }

        }
    });
}

From source file:cn.zy.ef.fragment.WebViewFragment.java

protected void configureWebView(WebSettings settings) {
    settings.setJavaScriptCanOpenWindowsAutomatically(true);//js??window.open()false
    settings.setJavaScriptEnabled(true);//??jsfalsetrue????XSS?
    settings.setSupportZoom(true);//??true
    settings.setBuiltInZoomControls(false);//?false
    settings.setUseWideViewPort(true);//???
    settings.setLoadWithOverviewMode(true);//setUseWideViewPort(true)
    settings.setAppCacheEnabled(true);//?
    settings.setDomStorageEnabled(true);//DOM Storage
    settings.setCacheMode(WebSettings.LOAD_DEFAULT);
}

From source file:com.quarterfull.newsAndroid.NewsDetailFragment.java

@SuppressLint("SetJavaScriptEnabled")
private void init_webView() {
    int backgroundColor = ColorHelper.getColorFromAttribute(getContext(), R.attr.news_detail_background_color);
    mWebView.setBackgroundColor(backgroundColor);

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setAllowFileAccess(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(false);
    webSettings.setSupportMultipleWindows(false);
    webSettings.setSupportZoom(false);//from  ww  w  .  ja  v a2 s  . c om
    webSettings.setAppCacheEnabled(true);

    registerForContextMenu(mWebView);

    mWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage cm) {
            Log.v(TAG, cm.message() + " at " + cm.sourceId() + ":" + cm.lineNumber());
            return true;
        }

        @Override
        public void onProgressChanged(WebView view, int progress) {
            if (progress < 100 && mProgressbarWebView.getVisibility() == ProgressBar.GONE) {
                mProgressbarWebView.setVisibility(ProgressBar.VISIBLE);
            }
            mProgressbarWebView.setProgress(progress);
            if (progress == 100) {
                mProgressbarWebView.setVisibility(ProgressBar.GONE);

                //The following three lines are a workaround for websites which don't use a background color
                int bgColor = ContextCompat.getColor(getContext(),
                        R.color.slider_listview_text_color_dark_theme);
                NewsDetailActivity ndActivity = ((NewsDetailActivity) getActivity());
                mWebView.setBackgroundColor(bgColor);
                ndActivity.mViewPager.setBackgroundColor(bgColor);

                if (ThemeChooser.isDarkTheme(getActivity())) {
                    mWebView.setBackgroundColor(
                            ContextCompat.getColor(getContext(), android.R.color.transparent));
                }
            }
        }
    });

    mWebView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (changedUrl) {
                changedUrl = false;

                if (!url.equals("file:///android_asset/") && (urls.isEmpty() || !urls.get(0).equals(url))) {
                    urls.add(0, url);

                    Log.v(TAG, "Page finished (added): " + url);
                }
            }

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

    mWebView.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (v.getId() == R.id.webview && event.getAction() == MotionEvent.ACTION_DOWN) {
                changedUrl = true;
            }

            return false;
        }
    });
}

From source file:io.selendroid.server.model.SelendroidWebDriver.java

private void configureWebView(final WebView view) {
    ServerInstrumentation.getInstance().getCurrentActivity().runOnUiThread(new Runnable() {

        @Override/*  w w  w  .j  a v  a 2 s  .c o m*/
        public void run() {
            try {
                view.clearCache(true);
                view.clearFormData();
                view.clearHistory();
                view.setFocusable(true);
                view.setFocusableInTouchMode(true);
                view.setNetworkAvailable(true);
                // need to check the class name rather than checking instanceof
                // since when it is not an instanceof, it likely means the app under test
                // does not contain the Cordova project and this will cause a RuntimeException
                if (view.getClass().getSimpleName().equalsIgnoreCase("CordovaWebView")) {
                    CordovaWebView webview = (CordovaWebView) view;
                    CordovaInterface ci = null;
                    chromeClient = new ExtendedCordovaChromeClient(null, webview);
                } else {
                    chromeClient = new SelendroidWebChromeClient();
                }
                view.setWebChromeClient(chromeClient);

                WebSettings settings = view.getSettings();
                settings.setJavaScriptCanOpenWindowsAutomatically(true);
                settings.setSupportMultipleWindows(true);
                settings.setBuiltInZoomControls(true);
                settings.setJavaScriptEnabled(true);
                settings.setAppCacheEnabled(true);
                settings.setAppCacheMaxSize(10 * 1024 * 1024);
                settings.setAppCachePath("");
                settings.setDatabaseEnabled(true);
                settings.setDomStorageEnabled(true);
                settings.setGeolocationEnabled(true);
                settings.setSaveFormData(false);
                settings.setSavePassword(false);
                settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
                // Flash settings
                settings.setPluginState(WebSettings.PluginState.ON);

                // Geo location settings
                settings.setGeolocationEnabled(true);
                settings.setGeolocationDatabasePath("/data/data/selendroid");
            } catch (Exception e) {
                SelendroidLogger.error("Error configuring web view", e);
            }
        }
    });
}

From source file:com.example.administrator.mywebviewdrawsign.SysWebView.java

/**
 * Initialize webview.// w  w w.  jav  a 2s  . co  m
 */
@SuppressLint({ "NewApi", "SetJavaScriptEnabled" })
private void setup() {
    this.setInitialScale(0);
    this.setVerticalScrollBarEnabled(true);
    this.setHorizontalScrollBarEnabled(true);
    this.requestFocusFromTouch();
    // Enable JavaScript
    WebSettings settings = this.getSettings();

    settings.setBuiltInZoomControls(false);// ??
    settings.setUseWideViewPort(false);
    settings.setLoadWithOverviewMode(true);
    settings.setJavaScriptEnabled(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);
    settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
    settings.setAllowFileAccess(true);
    settings.setAppCacheMaxSize(1024 * 1024 * 32);
    settings.setAppCachePath(mContext.getFilesDir().getPath() + "/cache");
    settings.setAppCacheEnabled(true);
    settings.setCacheMode(WebSettings.LOAD_DEFAULT);
    // Set Cache Mode: LOAD_NO_CACHE is noly for debug
    //settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    //enablePageCache(settings,5);
    //enableWorkers(settings);

    // Enable database
    settings.setDatabaseEnabled(true);
    String databasePath = mContext.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
    settings.setDatabasePath(databasePath);

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

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

    // Improve render performance
    settings.setRenderPriority(WebSettings.RenderPriority.HIGH);

    if (Build.VERSION.SDK_INT >= 21) {
        settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    }
}

From source file:com.nbplus.hybrid.BasicWebViewClient.java

/**
 * ??./*from w w  w .  j  ava 2  s. c o  m*/
 * @param activity : context
 * @param view : ?? 
 */
public BasicWebViewClient(Activity activity, WebView view, String alertTitleString, String confirmTitleString) {
    mWebView = view;
    mContext = activity;

    // This will handle downloading. It requires Gingerbread, though
    mDownloadManager = (DownloadManager) mContext.getSystemService(mContext.DOWNLOAD_SERVICE);
    mWebChromeClient = new BroadcastWebChromeClient();

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

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setGeolocationEnabled(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setDatabaseEnabled(true);
    // Use WideViewport and Zoom out if there is no viewport defined
    webSettings.setUseWideViewPort(true);
    webSettings.setLoadWithOverviewMode(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        webSettings.setMediaPlaybackRequiresUserGesture(false);
    }

    // Enable pinch to zoom without the zoom buttons
    webSettings.setBuiltInZoomControls(true);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
        // Hide the zoom controls for HONEYCOMB+
        webSettings.setDisplayZoomControls(false);
    }

    webSettings.setAppCacheEnabled(true);
    mWebView.clearCache(true);
    webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // Sets whether the WebView should allow third party cookies to be set.
        // Allowing third party cookies is a per WebView policy and can be set differently on different WebView instances.

        // Apps that target KITKAT or below default to allowing third party cookies.
        // Apps targeting LOLLIPOP or later default to disallowing third party cookies.
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.setAcceptThirdPartyCookies(mWebView, true);
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        mWebView.getSettings().setTextZoom(100);
    }

    if (StringUtils.isEmptyString(alertTitleString)) {
        mAlertTitleString = activity.getString(R.string.default_webview_alert_title);
    } else {
        mAlertTitleString = alertTitleString;
    }

    if (StringUtils.isEmptyString(confirmTitleString)) {
        mConfirmTitleString = activity.getString(R.string.default_webview_confirm_title);
    } else {
        mConfirmTitleString = confirmTitleString;
    }

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

        }
    });

    Log.d(TAG, ">> user agent = " + mWebView.getSettings().getUserAgentString());
}