Example usage for android.webkit WebSettings setCacheMode

List of usage examples for android.webkit WebSettings setCacheMode

Introduction

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

Prototype

public abstract void setCacheMode(@CacheMode int mode);

Source Link

Document

Overrides the way the cache is used.

Usage

From source file:net.niyonkuru.koodroid.webview.BlockingWebView.java

public static BlockingWebView createInstance(Context ctx) {
    BlockingWebView view = new BlockingWebView(ctx);

    WebSettings websettings = view.getSettings();

    websettings.setJavaScriptEnabled(true);
    websettings.setDatabaseEnabled(false);
    websettings.setDomStorageEnabled(false);
    websettings.setSupportZoom(false);/*  ww w  .j av a 2s  . c om*/
    websettings.setSavePassword(false);
    websettings.setSupportMultipleWindows(false);
    websettings.setAppCacheEnabled(false);
    websettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    websettings.setBlockNetworkImage(true);

    return view;
}

From source file:org.catnut.fragment.OAuthFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    // clear cache
    WebSettings settings = mWebView.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    settings.setSaveFormData(false);/*from   w  ww .j a va 2s  .c om*/
    mWebView.loadUrl(Manifest.getOAuthUri());
}

From source file:com.anxpp.blog.fragment.AboutFragment.java

@SuppressLint("SetJavaScriptEnabled")
private void initView() {
    webView = (WebView) getView().findViewById(R.id.webView);
    //      webView.setVisibility(View.GONE);
    webView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            Activity activity = getActivity();
            /**//from  w  w  w  .j a  v  a  2s  .  c  o  m
             * ?Fragment???
             * I am not sure why are you getting this error, 
             * i think it should be something like NullPointerException. 
             * Try next: 
             *     Evert time you calling getActivity() on Fragment instance you should be sure,
             *     that fragment is actually have this Activity. 
             *     Because when your webview is loading you are calling this function:
             * */
            if (activity == null)
                return;
            activity.setTitle("Loading..." + progress + "%");
            activity.setProgress(progress * 100);
            if (progress == 100) {
                activity.setTitle(R.string.app_name);
                webView.setVisibility(View.VISIBLE);
            }
        }
    });
    webView.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Toast("shouldOverrideUrlLoading");
            view.loadUrl(url);
            return true;
        }
    });
    //??
    WebSettings webSettings = webView.getSettings();
    //?
    //webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    //?js
    webSettings.setJavaScriptEnabled(true);
    //? ?
    webSettings.setUseWideViewPort(false); //??
    webSettings.setLoadWithOverviewMode(true); // ??
    webView.loadUrl("http://anxpp.com");
    //
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //trueWebViewfalse??
            view.loadUrl(url);
            return true; //false?
        }
    });
    webView.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) { // ?
                    webView.goBack(); //?
                    return true; //?
                }
            }
            return false;
        }
    });
}

From source file:com.tdispatch.passenger.fragment.OAuthFragment.java

@SuppressLint("SetJavaScriptEnabled")
@Override/*w w  w  . j ava2  s  . c  o m*/
protected void onPostCreateView() {

    View v = mFragmentView.findViewById(R.id.button_cancel);
    v.setOnClickListener(mOnClickListener);

    ProgressBar pb = (ProgressBar) mFragmentView.findViewById(R.id.progressbar);
    pb.setVisibility(View.GONE);

    mWebView = (WebView) mFragmentView.findViewById(R.id.webview);
    if (mWebView != null) {

        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.setWebChromeClient(new MyWebchromeClient());

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            mWebView.setOnTouchListener(mOnTouchListener);
        }

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setAppCacheEnabled(false);
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);

        CookieSyncManager.createInstance(mContext);
        CookieManager cm = CookieManager.getInstance();
        cm.setAcceptCookie(true);
        cm.removeAllCookie();

        try {
            ApiRequest req = new ApiRequest(Const.Api.OauthAuthUrl);
            req.addGetParam("key", Const.getApiKey());
            req.addGetParam("scope", "");
            req.addGetParam("response_type", "code");
            req.addGetParam("client_id", Const.getOAuthClientId());
            req.addGetParam("redirect_uri", mOAuthRedirectUrl);
            req.buildRequest();

            String url = req.getUrl();

            mWebView.loadUrl(url);

        } catch (Exception e) {
            WebnetLog.e("Failed to load oauth launch page...");
        }

    } else {
        WebnetLog.e("Failed to init WebView. Aborting");
        mHostActivity.oAuthCancelled();
    }
}

From source file:net.olejon.mdapp.MedicationNlhFragment.java

@SuppressLint("SetJavaScriptEnabled")
@Override//  www .  ja v a  2 s  .co  m
public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
    ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_medication_nlh, container, false);

    // Activity
    final Activity activity = getActivity();

    // Context
    final Context context = activity.getApplicationContext();

    // Tools
    final MyTools mTools = new MyTools(context);

    // Arguments
    Bundle bundle = getArguments();

    final String pageUri = bundle.getString("uri");

    // Progress bar
    final ProgressBar progressBar = (ProgressBar) activity
            .findViewById(R.id.medication_toolbar_progressbar_horizontal);

    // Toolbar
    final LinearLayout toolbarSearchLayout = (LinearLayout) activity
            .findViewById(R.id.medication_toolbar_search_layout);
    final EditText toolbarSearchEditText = (EditText) activity.findViewById(R.id.medication_toolbar_search);

    // Web view
    WEBVIEW = (WebView) viewGroup.findViewById(R.id.medication_nlh_content);

    WebSettings webSettings = WEBVIEW.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setAppCacheEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setAppCachePath(context.getCacheDir().getAbsolutePath());
    webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);

    WEBVIEW.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!mTools.isDeviceConnected()) {
                mTools.showToast(getString(R.string.device_not_connected), 0);
                return true;
            } else if (url.matches(".*/[^#]+#[^/]+$")) {
                WEBVIEW.loadUrl(url.replaceAll("#[^/]+$", ""));
                return true;
            } else if (url.matches("^https?://.*?\\.pdf$")) {
                mTools.downloadFile(view.getTitle(), url);
                return true;
            }

            return false;
        }
    });

    WEBVIEW.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                progressBar.setVisibility(View.INVISIBLE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(newProgress);

                toolbarSearchLayout.setVisibility(View.GONE);
                toolbarSearchEditText.setText("");
            }
        }
    });

    if (savedInstanceState == null) {
        WEBVIEW.loadUrl(pageUri);
    } else {
        WEBVIEW.restoreState(savedInstanceState);
    }

    return viewGroup;
}

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

/**
 * Sets up the UI. It consists if a single WebView.
 *//*from   w  ww.j a  va  2  s  . c  om*/
@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:org.jsharkey.oilcan.BrowserActivity.java

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    requestWindowFeature(Window.FEATURE_PROGRESS);
    setContentView(R.layout.act_browse);

    scriptdb = new ScriptDatabase(this);
    scriptdb.onUpgrade(scriptdb.getWritableDatabase(), -10, 10);

    webview = (WebView) findViewById(R.id.browse_webview);

    WebSettings settings = webview.getSettings();
    settings.setSavePassword(false);/* ww w  .ja  v a2s .c o  m*/
    settings.setSaveFormData(false);
    settings.setJavaScriptEnabled(true);
    settings.setSupportZoom(true);
    settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

    FrameLayout zoomholder = (FrameLayout) this.findViewById(R.id.browse_zoom);
    zoomholder.addView(webview.getZoomControls());
    webview.getZoomControls().setVisibility(View.GONE);

    webview.setWebViewClient(new OilCanClient());
    webview.setWebChromeClient(new OilCanChrome());

    webview.addJavascriptInterface(new IntentHelper(), "intentHelper");

    // load the last-viewed page into browser
    String url = "http://m.half.com/";
    if (icicle != null && icicle.containsKey(LAST_VIEWED))
        url = icicle.getString(LAST_VIEWED);

    // or watch for incoming requested urls
    if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(SearchManager.QUERY))
        url = getIntent().getStringExtra(SearchManager.QUERY);

    webview.loadUrl(url);

}

From source file:de.madvertise.android.sdk.MadvertiseMraidView.java

public MadvertiseMraidView(Context context) {
    super(context);
    setVerticalScrollBarEnabled(false);/* ww  w . ja v  a2 s  .  co m*/
    setHorizontalScrollBarEnabled(false);
    setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    setBackgroundColor(Color.TRANSPARENT);
    WebSettings settings = getSettings();
    settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    settings.setJavaScriptEnabled(true);
    //settings.setPluginsEnabled(true);

    // Initialize the default expand properties.
    DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
    mExpandProperties = new ExpandProperties(metrics.widthPixels, metrics.heightPixels);
    MadvertiseUtil.logMessage(null, Log.INFO,
            "Setting default expandProperties : " + mExpandProperties.toJson().toString());

    // This bridge stays available until this view is destroyed, hence no
    // reloading when displaying new ads is necessary.
    addJavascriptInterface(mBridge, "mraid_bridge");

    setWebViewClient(new WebViewClient() {
        private boolean mError = false;

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {
            post(new Runnable() {
                @Override
                public void run() {
                    if (mListener != null) {
                        mListener.onAdClicked();
                    }
                    final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url),
                            getContext().getApplicationContext(), MadvertiseActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    getContext().startActivity(intent);
                }
            });
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (!url.endsWith("mraid.js") && !mError) {
                MadvertiseUtil.logMessage(null, Log.DEBUG, "Setting mraid to default");
                checkReady();

                // Close button in default size for interstitial ads
                if (mPlacementType == MadvertiseUtil.PLACEMENT_TYPE_INTERSTITIAL) {
                    mCloseButton = addCloseButtonToViewGroup(((ViewGroup) getParent()));
                    mCloseButton.setImageResource(android.R.drawable.ic_menu_close_clear_cancel);
                }
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            mError = true;
        }
    });

    // Comment this in to enable video tag-capability.
    this.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            MadvertiseUtil.logMessage(null, Log.INFO, "showing VideoView");
            super.onShowCustomView(view, callback);
            if (view instanceof FrameLayout) {
                FrameLayout frame = (FrameLayout) view;
                if (frame.getFocusedChild() instanceof VideoView) {
                    mVideo = (VideoView) ((FrameLayout) view).getFocusedChild();
                    frame.removeView(mVideo);
                    ((ViewGroup) getParent()).addView(mVideo);

                    // Will also be called onError
                    mVideo.setOnCompletionListener(new OnCompletionListener() {

                        @Override
                        public void onCompletion(MediaPlayer player) {
                            player.stop();
                        }
                    });

                    mVideo.setOnErrorListener(new OnErrorListener() {

                        @Override
                        public boolean onError(MediaPlayer mp, int what, int extra) {
                            MadvertiseUtil.logMessage(null, Log.WARN, "Error while playing video");

                            if (mListener != null) {
                                mListener.onError(new IOException("Error while playing video"));
                            }

                            // We return false in order to call
                            // onCompletion()
                            return false;
                        }
                    });

                    mVideo.start();
                }
            }
        }

        @Override
        public void onHideCustomView() {
            if (mVideo != null) {
                ((ViewGroup) getParent()).removeView(mVideo);
                if (mVideo.isPlaying()) {
                    mVideo.stopPlayback();
                }
            }
        }
    });
}

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;/*  w  w w. jav  a 2 s .  c o  m*/
    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:com.rfo.basic.Web.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.v(LOGTAG, "onCreate");
    super.onCreate(savedInstanceState);
    ContextManager cm = Basic.getContextManager();
    cm.registerContext(ContextManager.ACTIVITY_WEB, this);
    cm.setCurrent(ContextManager.ACTIVITY_WEB);

    setContentView(R.layout.web);/*ww w .  j  ava  2  s  .  c o m*/
    View v = findViewById(R.id.web_engine);

    Intent intent = getIntent();
    int showStatusBar = intent.getIntExtra(EXTRA_SHOW_STATUSBAR, 0);
    int orientation = intent.getIntExtra(EXTRA_ORIENTATION, -1);

    showStatusBar = (showStatusBar == 0) ? WindowManager.LayoutParams.FLAG_FULLSCREEN // do not show status bar
            : WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN; // show status bar
    getWindow().setFlags(showStatusBar, showStatusBar);

    setOrientation(orientation);

    engine = (WebView) v;

    WebSettings webSettings = engine.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setBuiltInZoomControls(true);
    webSettings.setSupportZoom(true);
    webSettings.setAppCacheEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setAllowFileAccess(true);
    webSettings.setGeolocationEnabled(true);
    webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

    engine.addJavascriptInterface(new JavaScriptInterface(), "Android");

    engine.setWebViewClient(new MyWebViewClient());

    aWebView = new TheWebView(this);

    engine.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            //Required functionality here
            return super.onJsAlert(view, url, message, result);
        }
    });

}