Example usage for android.webkit WebSettings LOAD_CACHE_ELSE_NETWORK

List of usage examples for android.webkit WebSettings LOAD_CACHE_ELSE_NETWORK

Introduction

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

Prototype

int LOAD_CACHE_ELSE_NETWORK

To view the source code for android.webkit WebSettings LOAD_CACHE_ELSE_NETWORK.

Click Source Link

Document

Use cached resources when they are available, even if they have expired.

Usage

From source file:com.pursuer.reader.easyrss.VerticalSingleItemView.java

@SuppressLint("SetJavaScriptEnabled")
public void loadContent() {
    final WebSettings settings = webView.getSettings();
    settings.setDefaultTextEncodingName(HTTP.UTF_8);
    settings.setJavaScriptEnabled(true);
    settings.setDefaultFontSize(fontSize);
    settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    settings.setRenderPriority(RenderPriority.LOW);

    final StringBuffer content = new StringBuffer();
    if (item.getState().isCached()) {
        settings.setBlockNetworkImage(true);
        content.append(DataUtils.readFromFile(new File(item.getFullContentStoragePath())));
    } else {/*from  www.j ava 2  s  .  c o  m*/
        final SettingImageFetching sImgFetch = new SettingImageFetching(dataMgr);
        if (NetworkUtils.checkImageFetchingNetworkStatus(context, sImgFetch.getData())) {
            settings.setBlockNetworkImage(false);
            content.append(DataUtils.readFromFile(new File(item.getOriginalContentStoragePath())));
        } else {
            settings.setBlockNetworkImage(true);
            content.append(DataUtils.readFromFile(new File(item.getStrippedContentStoragePath())));
        }
    }
    content.append(DataUtils.DEFAULT_JS);
    content.append(
            theme == SettingTheme.THEME_NORMAL ? DataUtils.DEFAULT_NORMAL_CSS : DataUtils.DEFAULT_DARK_CSS);
    webView.loadDataWithBaseURL("file://" + item.getStoragePath() + "/", content.toString(), null, "utf-8",
            null);
}

From source file:org.mortbay.ijetty.IJetty.java

License:asdf

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

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);//?
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);//??

    MainApplication.getInstance().setAppHandler(mHandler);

    instance = this;
    mWebView = new HTML5WebView(this);
    mWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
    mWebView.setHorizontalScrollBarEnabled(false);//?
    mWebView.setVerticalScrollBarEnabled(false); //?

    mPropertiesUtil = new PropertiesUtils();

    //?/*from www . j  a v  a 2s . c o  m*/
    Intent autoStarIntent = new Intent("com.mortbay.ijetty.IJetty");
    autoStarIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    autoStarIntent.addFlags(32);
    sendBroadcast(autoStarIntent);

    //??
    //DisplayMetrics dm = new DisplayMetrics();
    //getWindowManager().getDefaultDisplay().getMetrics(dm);
    AppConstants.RESOLUTION = getDisplayScreenSize(); //String.valueOf(dm.widthPixels) + "*" + String.valueOf(getDisplayScreenHeight());    //dm.widthPixels,dm.heightPixels

    //??
    File clientProps = new File(IJetty.__JETTY_DIR + "/" + IJetty.__ETC_DIR + "/properties.xml");
    try {
        if (clientProps.exists() && clientProps.length() != 0) {
            //?assets??
            mPropertiesUtil.readPropertiesFileFromXML(
                    IJetty.getInstance().getBaseContext().getAssets().open("properties.xml"));
            //String propVersion = mPropertiesUtil.getVersion();
            Log.w("smallstar-defaultPropVersion", mPropertiesUtil.getVersion());
            int defaultPropVersion = Integer.parseInt(mPropertiesUtil.getVersion());
            mPropertiesUtil.readPropertiesFileFromXML(clientProps.getAbsolutePath());
            Log.w("smallstar-curPropVersion", mPropertiesUtil.getVersion());
            int curPropVersion = Integer.parseInt(mPropertiesUtil.getVersion());
            if (defaultPropVersion > curPropVersion) {
                //????????
                //TODO???
                mPropertiesUtil.readPropertiesFileFromXML(
                        IJetty.getInstance().getBaseContext().getAssets().open("properties.xml"));
                mPropertiesUtil.writePropertiesFileToXML(clientProps.getAbsolutePath());
                //?console.war
                Log.w(TAG, "copy console.warSD??");
                InputStream is = IJetty.getInstance().getBaseContext().getAssets().open("console.war");
                FileOutputStream fos = new FileOutputStream(AppConstants.getMediaSdFolder() + "/console.war");
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();
            }
            Log.w(TAG, "===========================================================");
            AppConstants.CLIENT_CUR_PLAYURL = mPropertiesUtil.getPlayUrl();
            Log.w(TAG, AppConstants.CLIENT_CUR_PLAYURL);
            Log.w(TAG, "===========================================================");
            //                Toast.makeText(IJetty.getInstance().getApplicationContext(), AppConstants.CLIENT_CUR_PLAYURL,
            //                        Toast.LENGTH_SHORT).show();

            PlayListUtil.playListVersion = mPropertiesUtil.getPlayListVersion();
            ApkUtils.apkPushVersion = mPropertiesUtil.getApkPushVersion();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.w("smallstar------>", "!clientProps.exists() error!!!!!!");
        e.printStackTrace();
    }

    //??:(?)
    startService(new Intent(this, DaemonService.class));

    //js?
    ProxyBridge jsBridge = new ProxyBridge(this);
    mWebView.addJavascriptInterface(jsBridge, "ia");

    mWebView.setHorizontalScrollBarEnabled(false);

    setContentView(R.layout.jetty_controller);

    startButton = (Button) findViewById(R.id.start);
    startButton.setVisibility(View.GONE);//??
    stopButton = (Button) findViewById(R.id.stop);
    stopButton.setVisibility(View.GONE);//??
    configButton = (Button) findViewById(R.id.config);
    configButton.setVisibility(View.GONE);//??
    final Button downloadButton = (Button) findViewById(R.id.download);
    downloadButton.setVisibility(View.GONE);//??

    IntentFilter filter = new IntentFilter();
    filter.addAction(__START_ACTION);
    filter.addAction(__STOP_ACTION);
    filter.addAction(__START_MOVIE_ACTION);
    filter.addCategory("default");

    bcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            if (__START_ACTION.equalsIgnoreCase(intent.getAction())) {
                startButton.setEnabled(false);
                configButton.setEnabled(false);
                stopButton.setEnabled(true);
                consolePrint("<br/>Started Jetty at %s", new Date());
                String[] connectors = intent.getExtras().getStringArray("connectors");
                if (null != connectors) {
                    for (int i = 0; i < connectors.length; i++)
                        consolePrint(connectors[i]);
                }

                printNetworkInterfaces();

                if (AndroidInfo.isOnEmulator(IJetty.this))
                    consolePrint("Set up port forwarding to see i-jetty outside of the emulator.");

                //warFile = new File("file:///android_asset/console.war");
                File file = new File(IJetty.__JETTY_DIR + "/" + IJetty.__WEBAPP_DIR + "/"
                        + "console/settings/basicsettings.html");
                if (file.exists()) {
                    if (file.length() > 0) {
                        //Not empty, do something here.
                        //i-jetty???web?
                        setContentView(mWebView.getLayout());
                        //TODO?????
                        int onlineTimeout = 0;
                        do {
                            if (onlineTimeout > 10)
                                break;
                            SystemClock.sleep(1000);
                            onlineTimeout++;
                        } while (!AppConstants.ONLINE_STATUS);

                        if (AppConstants.ONLINE_STATUS)//
                        {
                            mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                            //mWebView.getSettings().setCacheMode( WebSettings.LOAD_NO_CACHE);
                            mWebView.clearHistory();
                            mWebView.clearFormData();
                            mWebView.clearCache(true);
                            mWebView.loadUrl(AppConstants.CLIENT_CUR_PLAYURL);
                        } else
                            mWebView.loadUrl("http://localhost:8080/console/settings/basicsettings.html");
                    }
                }
            } else if (__STOP_ACTION.equalsIgnoreCase(intent.getAction())) {
                startButton.setEnabled(true);
                configButton.setEnabled(true);
                stopButton.setEnabled(false);
                consolePrint("<br/> Jetty stopped at %s", new Date());
            } else if (__START_MOVIE_ACTION.equalsIgnoreCase(intent.getAction())) {
                //service?onCreate()?onStartCommand().
                Log.i(TAG, "onReceive() get Broadcast org.mortbay.ijetty.movie.start");
                Intent mIntent = new Intent("createUI");
                mIntent.setClass(context, MediaPlaybackService.class);
                context.startService(mIntent);
            }
        }

    };

    registerReceiver(bcastReceiver, filter);

    // Watch for button clicks.
    startButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if (isUpdateNeeded())
                IJettyToast.showQuickToast(IJetty.this, R.string.loading);
            else {
                //TODO get these values from editable UI elements
                Intent intent = new Intent(IJetty.this, IJettyService.class);
                intent.putExtra(__PORT, __PORT_DEFAULT);
                intent.putExtra(__NIO, __NIO_DEFAULT);
                intent.putExtra(__SSL, __SSL_DEFAULT);
                intent.putExtra(__CONSOLE_PWD, __CONSOLE_PWD_DEFAULT);
                startService(intent);
            }
        }
    });

    stopButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            stopService(new Intent(IJetty.this, IJettyService.class));
        }
    });

    configButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            IJettyEditor.show(IJetty.this);
        }
    });

    downloadButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            IJettyDownloader.show(IJetty.this);
        }
    });

    info = (TextView) findViewById(R.id.info);
    info.setVisibility(View.GONE);
    footer = (TextView) findViewById(R.id.footer);
    footer.setVisibility(View.GONE);
    console = (TextView) findViewById(R.id.console);
    console.setVisibility(View.GONE);
    consoleScroller = (ScrollView) findViewById(R.id.consoleScroller);
    consoleScroller.setVisibility(View.GONE);

    StringBuilder infoBuffer = new StringBuilder();
    try {
        PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
        infoBuffer.append(formatJettyInfoLine("i-jetty version %s (%s)", pi.versionName, pi.versionCode));
    } catch (NameNotFoundException e) {
        infoBuffer.append(formatJettyInfoLine("i-jetty version unknown"));
    }
    infoBuffer.append(formatJettyInfoLine("On %s using Android version %s", AndroidInfo.getDeviceModel(),
            AndroidInfo.getOSVersion()));
    info.setText(Html.fromHtml(infoBuffer.toString()));

    StringBuilder footerBuffer = new StringBuilder();
    footerBuffer.append(
            "<b>Project:</b> <a href=\"http://code.google.com/p/i-jetty\">http://code.google.com/p/i-jetty</a> <br/>");
    footerBuffer.append("<b>Server:</b> http://www.eclipse.org/jetty <br/>");
    footerBuffer.append("<b>Support:</b> http://www.intalio.com/jetty/services <br/>");
    footer.setText(Html.fromHtml(footerBuffer.toString()));

    //??WEB?
    Intent intent = new Intent(IJetty.this, IJettyService.class);
    intent.putExtra(__PORT, __PORT_DEFAULT);
    intent.putExtra(__NIO, __NIO_DEFAULT);
    intent.putExtra(__SSL, __SSL_DEFAULT);
    intent.putExtra(__CONSOLE_PWD, __CONSOLE_PWD_DEFAULT);
    startService(intent);
}

From source file:org.chromium.android_webview.test.AwSettingsTest.java

@SmallTest
@Feature({ "AndroidWebView", "Preferences" })
public void testCacheMode() throws Throwable {
    final TestAwContentsClient contentClient = new TestAwContentsClient();
    final AwTestContainerView testContainer = createAwTestContainerViewOnMainSync(contentClient);
    final AwContents awContents = testContainer.getAwContents();
    final AwSettings awSettings = getAwSettingsOnUiThread(testContainer.getAwContents());
    clearCacheOnUiThread(awContents, true);

    assertEquals(WebSettings.LOAD_DEFAULT, awSettings.getCacheMode());
    TestWebServer webServer = null;/*from   w  w  w . j a  v a2 s .  c o  m*/
    try {
        webServer = new TestWebServer(false);
        final String htmlPath = "/testCacheMode.html";
        final String url = webServer.setResponse(htmlPath, "response", null);
        awSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        loadUrlSync(awContents, contentClient.getOnPageFinishedHelper(), url);
        assertEquals(1, webServer.getRequestCount(htmlPath));
        loadUrlSync(awContents, contentClient.getOnPageFinishedHelper(), url);
        assertEquals(1, webServer.getRequestCount(htmlPath));

        awSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        loadUrlSync(awContents, contentClient.getOnPageFinishedHelper(), url);
        assertEquals(2, webServer.getRequestCount(htmlPath));
        loadUrlSync(awContents, contentClient.getOnPageFinishedHelper(), url);
        assertEquals(3, webServer.getRequestCount(htmlPath));

        awSettings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);
        loadUrlSync(awContents, contentClient.getOnPageFinishedHelper(), url);
        assertEquals(3, webServer.getRequestCount(htmlPath));
        loadUrlSync(awContents, contentClient.getOnPageFinishedHelper(), url);
        assertEquals(3, webServer.getRequestCount(htmlPath));

        final String htmlNotInCachePath = "/testCacheMode-not-in-cache.html";
        final String urlNotInCache = webServer.setResponse(htmlNotInCachePath, "", null);
        loadUrlSyncAndExpectError(awContents, contentClient.getOnPageFinishedHelper(),
                contentClient.getOnReceivedErrorHelper(), urlNotInCache);
        assertEquals(0, webServer.getRequestCount(htmlNotInCachePath));
    } finally {
        if (webServer != null)
            webServer.shutdown();
    }
}

From source file:org.chromium.android_webview.test.AwSettingsTest.java

@SmallTest
@Feature({ "AndroidWebView", "Preferences" })
// As our implementation of network loads blocking uses the same net::URLRequest settings, make
// sure that setting cache mode doesn't accidentally enable network loads.  The reference
// behaviour is that when network loads are blocked, setting cache mode has no effect.
public void testCacheModeWithBlockedNetworkLoads() throws Throwable {
    final TestAwContentsClient contentClient = new TestAwContentsClient();
    final AwTestContainerView testContainer = createAwTestContainerViewOnMainSync(contentClient);
    final AwContents awContents = testContainer.getAwContents();
    final AwSettings awSettings = getAwSettingsOnUiThread(testContainer.getAwContents());
    clearCacheOnUiThread(awContents, true);

    assertEquals(WebSettings.LOAD_DEFAULT, awSettings.getCacheMode());
    awSettings.setBlockNetworkLoads(true);
    TestWebServer webServer = null;//www .j  av a2  s  .c o  m
    try {
        webServer = new TestWebServer(false);
        final String htmlPath = "/testCacheModeWithBlockedNetworkLoads.html";
        final String url = webServer.setResponse(htmlPath, "response", null);
        loadUrlSyncAndExpectError(awContents, contentClient.getOnPageFinishedHelper(),
                contentClient.getOnReceivedErrorHelper(), url);
        assertEquals(0, webServer.getRequestCount(htmlPath));

        awSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        loadUrlSyncAndExpectError(awContents, contentClient.getOnPageFinishedHelper(),
                contentClient.getOnReceivedErrorHelper(), url);
        assertEquals(0, webServer.getRequestCount(htmlPath));

        awSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        loadUrlSyncAndExpectError(awContents, contentClient.getOnPageFinishedHelper(),
                contentClient.getOnReceivedErrorHelper(), url);
        assertEquals(0, webServer.getRequestCount(htmlPath));

        awSettings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);
        loadUrlSyncAndExpectError(awContents, contentClient.getOnPageFinishedHelper(),
                contentClient.getOnReceivedErrorHelper(), url);
        assertEquals(0, webServer.getRequestCount(htmlPath));
    } finally {
        if (webServer != null)
            webServer.shutdown();
    }
}