本文介绍了web视图不显示网站时,离线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序使用GCM推送通知的注册。这code正常工作,而不是我的问题的根源。一旦注册成功,该应用程序只显示在一个web视图网站。到目前为止好这一切,如果该设备的网络适配器已开启工作。

如果网络适配器关闭然后web视图应该载入从缓存中。这部分是行不通的。我按照下面的教程,并在一个位取零件它保存的网页中保存在SD卡缓存。

如果我运行的应用程序的网站显示。如果我再关闭网络适配器和访问该网站,它不会显示。我检查了SD卡和部分网站的缓存目录已经被写入到缓存中。

为什么从缓存中没有该网站的负载时,脱线?

是否有可能保持它的网页缓存,直到说应用程序被卸载或Android另有决定?

教程

本教程介绍如何创建对SD卡的目录和写入。该目录确实存在,但web视图不是从这个缓存在离线模式下恢复。

下面

我是如何调用,显示的WebView的mainactivity。

 意向书我=新的意向书(getApplicationContext(),MainActivity.class);
                //i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                i.putExtra(名,硬codeD客户名称);
                i.putExtra(电子邮件,硬codeD电子邮件);
                startActivity(ⅰ);
                完();
 

下面是完整的MainActivity。您可以忽略第一部分,因为这是在code表示处理GCM推送通知的东西,所有的作品。我需要知道为什么web视图不会从缓存中加载。

 进口静电com.bmi.bmitestapp.CommonUtilities.DISPLAY_MESSAGE_ACTION;
引入静态com.bmi.bmitestapp.CommonUtilities.EXTRA_MESSAGE;
引入静态com.bmi.bmitestapp.CommonUtilities.SENDER_ID;

进口的java.io.File;

进口android.app.Activity;
进口android.content.BroadcastReceiver;
进口android.content.Context;
进口android.content.Intent;
进口android.content.IntentFilter;
进口android.net.ConnectivityManager;
进口android.net.NetworkInfo;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.util.Log;
进口android.webkit.WebChromeClient;
进口android.webkit.WebSettings;
进口android.webkit.WebView;
进口android.webkit.WebViewClient;
进口android.widget.TextView;
进口android.widget.Toast;
进口android.webkit *。


进口com.google.android.gcm.GCMRegistrar;

公共类MainActivity延伸活动{
    私有静态最后字符串变量= MainActivity.class.getSimpleName();
    //标签显示GCM消息
    TextView的lblMessage;
    的WebView web视图;
    // Asyntask
    AsyncTask的<虚空,虚空,虚空> mRegisterTask;

    //警报对话框经理
    AlertDialogManager警报=新AlertDialogManager();

    //连接器
    ConnectionDetector CD;

    公共静态字符串名称;
    公共静态字符串的电子邮件;

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);

        (中的onCreate在mainactivity标签)Log.e;
        CD =新ConnectionDetector(getApplicationContext());

        //检查网络present
//如果(!cd.isConnectingToInternet()){
// // Internet连接没有present
// alert.showAlertDialog(MainActivity.this,
//Internet连接错误,
//请连接到Internet连接,假);
// //停止执行返回code
//            返回;
//}

        //获取来自意图的姓名,电子邮件
        意图I = getIntent();

        名称= i.getStringExtra(姓名);
        电子邮件= i.getStringExtra(电子邮件);

        //确保设备具有适当的依赖关系。
        GCMRegistrar.checkDevice(本);

        //确保清单中正确设置 - 这一行注释掉
        //而开发的应用程序,然后去掉它时,它已经准备好。
        GCMRegistrar.checkManifest(本);

        lblMessage =(TextView中)findViewById(R.id.lblMessage);

        registerReceiver(mHandleMessageReceiver,新的IntentFilter(
                DISPLAY_MESSAGE_ACTION));

        //获取GCM注册ID
        最后弦乐REGID = GCMRegistrar.getRegistrationId(本);

        //检查REGID已经presents
        如果(regId.equals()){
            //注册是不是present,与GCM现在注册
            GCMRegistrar.register(这一点,SENDER_ID);
        } 其他 {
            //设备已经在GCM注册
            如果(GCMRegistrar.isRegisteredOnServer(本)){
                //跳过注册。
                Toast.makeText(getApplicationContext(),与GCM已经注册,Toast.LENGTH_LONG).show();
            } 其他 {
                //尝试重新注册,而不是在UI线程。
                //这也是必要取消线程的onDestroy()
                //因此使用原纱的AsyncTask代替。
                最终的上下文语境=这一点;
                mRegisterTask =新的AsyncTask<虚空,虚空,虚空>(){

                    @覆盖
                    保护无效doInBackground(虚空...... PARAMS){
                        //注册我们的服务器上
                        //在服务器上创建一个新用户
                        ServerUtilities.register(上下文,姓名,电子邮件,REGID);
                        返回null;
                    }

                    @覆盖
                    保护无效onPostExecute(无效的结果){
                        mRegisterTask = NULL;
                    }

                };
                mRegisterTask.execute(NULL,NULL,NULL);
            }
        }

            web视图=(web视图)findViewById(R.id.webView1);
            //初始化的WebView
            。webView.getSettings()setSupportZoom(真正的);
            。webView.getSettings()setBuiltInZoomControls(真正的);
            webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
            webView.setScrollbarFadingEnabled(真正的);
            。webView.getSettings()setLoadsImagesAutomatically(真正的);





            webView.getSettings()setDomStorageEnabled(真)。

            //设置缓存大小为8 MB默认情况下。应该是绰绰有余
            webView.getSettings()setAppCacheMaxSize(1024 * 1024 * 8)。

            //这下一个是疯了。这是为你的应用程序缓存的默认位置
            //但是,这并不适合我没有这条线的工作。
            //更新:没有硬性codeD路径。由于凯文·霍金斯
            字符串appCachePath = getApplicationContext()getCacheDir()getAbsolutePath()。
            Log.e(TAG,appCachePath =+ appCachePath);
            webView.getSettings()setAppCachePath(appCachePath)。
            。webView.getSettings()setAllowFileAccess(真正的);
            webView.getSettings()setAppCacheEnabled(真)。




            //加载的URL web视图内,而不是在外部Web浏览器
            webView.setWebViewClient(新WebViewClient());

            如果(savedInstanceState == NULL)
                        {



        如果(isNetworkAvailable()==真){
            Log.e(TAG,我们有一个网络连接);
            。webView.getSettings()setCacheMode(WebSettings.LOAD_DEFAULT);

            webView.loadUrl(http://bmi.cubecore.co.uk);


        } 其他 {
            Log.e(TAG,我们没有网络连接);
            。webView.getSettings()setCacheMode(WebSettings.LOAD_CACHE_ONLY);

            webView.loadUrl(http://bmi.cubecore.co.uk);
        }


                        }

    在OnCreate的} //结束


    私人布尔isNetworkAvailable(){
        ConnectivityManager connectivityManager =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        的NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        返回activeNetworkInfo!= NULL;
    }


    / **
     *接收推送消息
     * * /
    私人最终的BroadcastReceiver mHandleMessageReceiver =新的BroadcastReceiver(){
        @覆盖
        公共无效的onReceive(上下文的背景下,意图意图){
            字符串NewMessage作为= intent.getExtras()的getString(EXTRA_MESSAGE)。
            //醒来移动,如果它是睡
            WakeLocker.acquire(getApplicationContext());

            / **
             *采取适当行动此消息
             *根据您的应用需求
             *现在我只是在屏幕上显示出来
             * * /

            //显示接收到的消息
            lblMessage.append(NewMessage作为+\ N);
            Toast.makeText(getApplicationContext(),新邮件+ NewMessage作为,Toast.LENGTH_LONG).show();

            //释放唤醒锁
            WakeLocker.release();
        }
    };

    @覆盖
    保护无效的onDestroy(){
        super.onDestroy();

        //清除缓存(这将清除WebViews缓存为整个应用程序)
        //webView.clearCache(false);

        如果(mRegisterTask!= NULL){
            mRegisterTask.cancel(真正的);
        }
        尝试 {
            unregisterReceiver(mHandleMessageReceiver);
            GCMRegistrar.onDestroy(本);
        }赶上(例外五){
            Log.e(注销接收器错误,>中+ e.getMessage());
        }



    }



    @覆盖
    公共无效onBack pressed(){
        super.onBack pressed();


    }

    @覆盖
    保护无效onResume(){
        super.onResume();
        (在onResume中mainactivity标签)Log.e;

    }



    @覆盖
    公共文件getCacheDir()
    {
        //注:此方法采用的是Android 2.1
Log.e(TAG,getcachedir);
        返回getApplicationContext()getCacheDir()。
    }

    @覆盖
    保护无效的onSaveInstanceState(包outState)
    {
        super.onSaveInstanceState(outState);

        //保存web视图状态
        webView.saveState(outState);
    }

    @覆盖
    保护无效onRestoreInstanceState(包savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);

        //恢复的WebView的状态
        webView.restoreState(savedInstanceState);
    }

}
 

下面是本教程的code以上的写入SD卡。

 包com.bmi.bmitestapp;

进口的java.io.File;

进口android.app.Application;
进口android.os.Environment;
进口android.util.Log;

公共类ApplicationExt扩展应用
{
    私有静态最后字符串变量= ApplicationExt.class.getSimpleName();
    //注:此路径的内容将被删除
    //当卸载应用程序(Android 2.2及更高版本)
    受保护的文件extStorageAppBasePath;

    受保护的文件extStorageAppCachePath;

    @覆盖
    公共无效的onCreate()
    {
        super.onCreate();
         Log.e(TAG,里面appext);
        //检查外部存储可写
        如果(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
        {

            //获得基路径在外部存储的应用程序
            文件externalStorageDir = Environment.getExternalStorageDirectory();

            如果(externalStorageDir!= NULL)
            {
                // {SD_PATH} /Android/data/com.devahead.androidwebviewcacheonsd
                extStorageAppBasePath =新的文件(externalStorageDir.getAbsolutePath()+
                    文件分割符+Android的+文件分割符+数据+
                    文件分割符+ getPackageName());
            }

            如果(extStorageAppBasePath!= NULL)
            {
                // {SD_PATH} /Android/data/com.devahead.androidwebviewcacheonsd/cache
                extStorageAppCachePath =新的文件(extStorageAppBasePath.getAbsolutePath()+
                    文件分割符+缓存);

                布尔isCachePathAvailable =真;

                如果(!extStorageAppCachePath.exists())
                {
                    //创建在外部存储器中的高速缓存路径
                    isCachePathAvailable = extStorageAppCachePath.mkdirs();
                }

                如果(!isCachePathAvailable)
                {
                    //无法创建缓存路径
                    extStorageAppCachePath = NULL;
                }
            }
        }
    }

    @覆盖
    公共文件getCacheDir()
    {
        //注:此方法采用的是Android 2.2及更高版本

        如果(extStorageAppCachePath!= NULL)
        {
            //使用外部存储高速缓存
            Log.e(TAG,extStorageAppCachePath =+ extStorageAppCachePath);
            返回extStorageAppCachePath;
        }
        其他
        {
            // /data/data/com.devahead.androidwebviewcacheonsd/cache
            返回super.getCacheDir();
        }
    }
}
 

我想我有一个小记录。这是一个新的记录安装的网络适配器上。

  01-29 14:13:10.220:D / dalvikvm(16904):晚启用CheckJNI
01-29 14:13:10.470:E / ApplicationExt(16904):内appext
01-29 14:13:10.720:E / RegisterActivity(16904):在onresume在registeractivity
01-29 14:13:10.880:D / libEGL(16904):加载/system/lib/egl/libEGL_tegra.so
01-29 14:13:11.000:D / libEGL(16904):加载/system/lib/egl/libGLESv1_CM_tegra.so
01-29 14:13:11.030:D / libEGL(16904):加载/system/lib/egl/libGLESv2_tegra.so
01-29 14:13:11.070:D / OpenGLRenderer(16904):启用调试模式0
01-29 14:13:18.390:E / ApplicationExt(16904):extStorageAppCachePath = /mnt/sdcard/Android/data/com.bmi.bmitestapp/cache
01-29 14:13:18.390:D / web视图(16904):[InitTabEffectPivot]≥> nScreenWidth = 720
01-29 14:13:18.390:D / web视图(16904):[InitTabEffectPivot]≥> nScreenHeight = 1280
01-29 14:13:18.390:D / SqliteDatabaseCpp(16904):注册sqlite的记录FUNC:/data/data/com.bmi.bmitestapp/databases/webview.db
01-29 14:13:18.390:D / SqliteDatabaseCpp(16904):数据库信息:打开数据库,路径= /data/data/com.bmi.bmitestapp/databases,关键= sefraes,标志= 6,不能与stat文件,错误号= 2,消息=没有这样的文件或目录
01-29 14:13:18.400:E / MainActivity(16904):在的onCreate在mainactivity
01-29 14:13:18.400:D / SqliteDatabaseCpp(16904):数据库的信息:PATH = /data/data/com.bmi.bmitestapp/databases,关键= sefraes,处理:0x1f9a858,类型:W,R / W: (0,1),模式:删除,磁盘可用空间:1276中号
01-29 14:13:18.400:D / GCMRegistrar(16904):重置退避的com.bmi.bmitestapp
01-29 14:13:18.420:V / GCMRegistrar(16904):注册发件人598080744593的应用程序com.bmi.bmitestapp
01-29 14:13:18.430:E / ApplicationExt(16904):extStorageAppCachePath = /mnt/sdcard/Android/data/com.bmi.bmitestapp/cache
01-29 14:13:18.430:E / MainActivity(16904):appCachePath = /mnt/sdcard/Android/data/com.bmi.bmitestapp/cache
01-29 14:13:18.430:E / MainActivity(16904):我们有一个网络连接
01-29 14:13:18.430:E / MainActivity(16904):在onResume在mainactivity
01-29 14:13:18.490:W / WebCore的(16904):java.lang.Throwable中:EventHub.removeMessages(INT什么= 107),不支持前WebViewCore设置。
01-29 14:13:18.490:W / WebCore的(16904):在android.webkit.WebViewCore $ EventHub.removeMessages(WebViewCore.java:1974)
01-29 14:13:18.490:W / WebCore的(16904):在android.webkit.WebViewCore $ EventHub.access $ 9100(W​​ebViewCore.java:1008)
01-29 14:13:18.490:W / WebCore的(16904):在android.webkit.WebViewCore.removeMessages(WebViewCore.java:2215)
01-29 14:13:18.490:W / WebCore的(16904):在android.webkit.WebView.sendOurVisibleRect(WebView.java:3285)
01-29 14:13:18.490:W / WebCore的(16904):在android.webkit.ZoomManager.setZoomScale(ZoomManager.java:772)
01-29 14:13:18.490:W / WebCore的(16904):在android.webkit.ZoomManager.access $ 1900年(ZoomManager.java:59)
01-29 14:13:18.490:W / WebCore的(16904):在android.webkit.ZoomManager $ PostScale.run(ZoomManager.java:1345)
01-29 14:13:18.490:W / WebCore的(16904):在android.os.Handler.handleCallback(Handler.java:608)
01-29 14:13:18.490:W / WebCore的(16904):在android.os.Handler.dispatchMessage(Handler.java:92)
01-29 14:13:18.490:W / WebCore的(16904):在android.os.Looper.loop(Looper.java:156)
01-29 14:13:18.490:W / WebCore的(16904):在android.app.ActivityThread.main(ActivityThread.java:5045)
01-29 14:13:18.490:W / WebCore的(16904):在java.lang.reflect.Method.invokeNative(本机方法)
01-29 14:13:18.490:W / WebCore的(16904):在java.lang.reflect.Method.invoke(Method.java:511)
01-29 14:13:18.490:W / WebCore的(16904):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784)
01-29 14:13:18.490:W / WebCore的(16904):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-29 14:13:18.490:W / WebCore的(16904):在dalvik.system.NativeStart.main(本机方法)
01-29 14:13:18.500:W / WebCore的(16904):java.lang.Throwable中:EventHub.removeMessages(INT什么= 105),不支持前WebViewCore设置。
01-29 14:13:18.500:W / WebCore的(16904):在android.webkit.WebViewCore $ EventHub.removeMessages(WebViewCore.java:1974)
01-29 14:13:18.500:W / WebCore的(16904):在android.webkit.WebViewCore $ EventHub.access $ 9100(W​​ebViewCore.java:1008)
01-29 14:13:18.500:W / WebCore的(16904):在android.webkit.WebViewCore.removeMessages(WebViewCore.java:2215)
01-29 14:13:18.500:W / WebCore的(16904):在android.webkit.WebView.sendViewSizeZoom(WebView.java:3520)
01-29 14:13:18.500:W / WebCore的(16904):在android.webkit.ZoomManager.setZoomScale(ZoomManager.java:778)
01-29 14:13:18.500:W / WebCore的(16904):在android.webkit.ZoomManager.access $ 1900年(ZoomManager.java:59)
01-29 14:13:18.500:W / WebCore的(16904):在android.webkit.ZoomManager $ PostScale.run(ZoomManager.java:1345)
01-29 14:13:18.500:W / WebCore的(16904):在android.os.Handler.handleCallback(Handler.java:608)
01-29 14:13:18.500:W / WebCore的(16904):在android.os.Handler.dispatchMessage(Handler.java:92)
01-29 14:13:18.500:W / WebCore的(16904):在android.os.Looper.loop(Looper.java:156)
01-29 14:13:18.500:W / WebCore的(16904):在android.app.ActivityThread.main(ActivityThread.java:5045)
01-29 14:13:18.500:W / WebCore的(16904):在java.lang.reflect.Method.invokeNative(本机方法)
01-29 14:13:18.500:W / WebCore的(16904):在java.lang.reflect.Method.invoke(Method.java:511)
01-29 14:13:18.500:W / WebCore的(16904):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784)
01-29 14:13:18.500:W / WebCore的(16904):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-29 14:13:18.500:W / WebCore的(16904):在dalvik.system.NativeStart.main(本机方法)
01-29 14:13:18.530:D / OpenGLRenderer(16904):刷新缓存(模式0)
01-29 14:13:18.570:I / SqliteDatabaseCpp(16904):源码返回:错误code = 1,味精=没有这样的表:CacheGroups
01-29 14:13:18.570:I / SqliteDatabaseCpp(16904):源码返回:错误code = 1,味精=没有这样的表:缓存
01-29 14:13:18.570:I / SqliteDatabaseCpp(16904):源码返回:错误code = 1,味精=没有这样的表:起源
01-29 14:13:18.570:I / SqliteDatabaseCpp(16904):源码返回:错误code = 1,味精=没有这样的表:DeletedCacheResources
01-29 14:13:18.850:E / ApplicationExt(16904):extStorageAppCachePath = /mnt/sdcard/Android/data/com.bmi.bmitestapp/cache
01-29 14:13:19.330的:I / PRIME(16904):其中; CallBackProxy>发送到WebViewClient。
01-29 14:13:19.370:V / GCMBroadcastReceiver(16904):的onReceive:com.google.android.c2dm.intent.REGISTRATION
01-29 14:13:19.370:V / GCMBroadcastReceiver(16904):GCM IntentService类:com.bmi.bmitestapp.GCMIntentService
01-29 14:13:19.370:V / GCMBaseIntentService(16904):获取wakelock
01-29 14:13:19.460:V / GCMBaseIntentService(16904):意图服务名称:GCMIntentService-598080744593-1
01-29 14:13:19.470:E / GCMRegistrar(16904):内部错误:重试接收器类还没有设置
01-29 14:13:19.480:V / GCMRegistrar(16904):注册接收机
01-29 14:13:19.480:D / GCMBaseIntentService(16904):handleRegistration:registrationId = APA91bFytZvnkmsEVHSnw5VRxIwfPRmPsSRVrgRNRa5ww3oqCfnLEZMaBBNtQtlZoK4RD4VQXfAfKDsQUa53PwQBH_rwuI_gEEdHQhxadpBVmJ7L3Dxy90Bzryg_aCWx20-cdZ32cbiiaGR3zUMjpqZizYQbnARN4w,错误= NULL,未注册= NULL
01-29 14:13:19.480:D / GCMRegistrar(16904):重置退避的com.bmi.bmitestapp
01-29 14:13:19.480:V / GCMRegistrar(16904):保存REGID上的应用程序版本1
01-29 14:13:19.490:I / GCMIntentService(16904):设备注册:REGID = APA91bFytZvnkmsEVHSnw5VRxIwfPRmPsSRVrgRNRa5ww3oqCfnLEZMaBBNtQtlZoK4RD4VQXfAfKDsQUa53PwQBH_rwuI_gEEdHQhxadpBVmJ7L3Dxy90Bzryg_aCWx20-cdZ32cbiiaGR3zUMjpqZizYQbnARN4w
01-29 14:13:19.490:D / NAME(16904):硬codeD的客户端名称
01-29 14:13:19.490:I / BMI GCM(16904):注册设备(REGID = APA91bFytZvnkmsEVHSnw5VRxIwfPRmPsSRVrgRNRa5ww3oqCfnLEZMaBBNtQtlZoK4RD4VQXfAfKDsQUa53PwQBH_rwuI_gEEdHQhxadpBVmJ7L3Dxy90Bzryg_aCWx20-cdZ32cbiiaGR3zUMjpqZizYQbnARN4w)
01-29 14:13:19.490:D / BMI GCM(16904):尝试#1登记
01-29 14:13:19.500:V / BMI GCM(16904):发帖的电子邮件=硬codeD email&regId=APA91bFytZvnkmsEVHSnw5VRxIwfPRmPsSRVrgRNRa5ww3oqCfnLEZMaBBNtQtlZoK4RD4VQXfAfKDsQUa53PwQBH_rwuI_gEEdHQhxadpBVmJ7L3Dxy90Bzryg_aCWx20-cdZ32cbiiaGR3zUMjpqZizYQbnARN4w&name=hard$c$cd客户端名称来http://mobilewebexpert.co.uk/pushtest/register.php
01-29 14:13:19.500:E / URL(16904):> http://mobilewebexpert.co.uk/pushtest/register.php
01-29 14:13:20.610:V / GCMRegistrar(16904):设置registeredOnServer状态为真,直到2013年2月5日14:13:20.617
01-29 14:13:20.620:V / GCMBaseIntentService(16904):释放wakelock
01-29 14:13:21.470:D / Skia的(16904):notifyPluginsOnFrameLoad不推迟
01-29 14:13:21.570:D / SQLiteDatabase(16904):创建池连接
01-29 14:13:21.570:D / SqliteDatabaseCpp(16904):数据库信息:打开数据库,路径= /data/data/com.bmi.bmitestapp/databases,关键= sefraes,标志= 1,文件大小= 12288
01-29 14:13:21.570:D / SqliteDatabaseCpp(16904):数据库的信息:PATH = /data/data/com.bmi.bmitestapp/databases,关键= sefraes,处理:0x2797350,类型:R,R / W: (1,1),模式:沃尔玛,硬盘可用空间:1276中号
 

这是记录后,我已经关闭的网络适配器。

  01-29 14:16:57.080:E / RegisterActivity(16904):在onresume在registeractivity
01-29 14:17:03.490:D / web视图(16904):[InitTabEffectPivot]≥> nScreenWidth = 720
01-29 14:17:03.490:D / web视图(16904):[InitTabEffectPivot]≥> nScreenHeight = 1280
01-29 14:17:03.490:E / MainActivity(16904):在的onCreate在mainactivity
01-29 14:17:03.490:V / GCMRegistrar(16904):注册服务器:真
01-29 14:17:03.500:E / ApplicationExt(16904):extStorageAppCachePath = /mnt/sdcard/Android/data/com.bmi.bmitestapp/cache
01-29 14:17:03.500:E / MainActivity(16904):appCachePath = /mnt/sdcard/Android/data/com.bmi.bmitestapp/cache
01-29 14:17:03.500:E / MainActivity(16904):我们没有网络连接
01-29 14:17:03.500:E / MainActivity(16904):在onResume在mainactivity
01-29 14:17:03.500:D /铬(16904):未知铬错误:-400
01-29 14:17:03.540:D / Skia的(16904):notifyPluginsOnFrameLoad不推迟
01-29 14:17:03.580:D / OpenGLRenderer(16904):刷新缓存(模式0)
 

有一件事情我已经注意到了,这可能不算什么,但registeractivity是调用MainActivity活动。 RegisterActivity只是有一个按钮,触发一个意图MainActivity。当网络适配器关闭我要preSS上registerAcivity按钮,这在MainActivity调用的onCreate。这就像它是MainActivity的新实例??难道这是影响web视图的缓存。有效的主要活动的onDestroy必须已经调用沿途。

还有另一件事情已经引起了我的注意。

  01-29 14:17:03.580:D / OpenGLRenderer(16904):刷新缓存(模式0)
 

解决方案

对于特定的URL http://bmi.cubecore.co.uk ,你的WebView的缓存禁止通过该HTTP服务器,请参阅响应头的Cache-Control

  200 OK
......
杂注:无缓存
服务器:Apache / 2.2.3(CentOS的)
内容类型:text / html的;字符集= UTF-8
缓存控制:无店面,无缓存,必重新验证,后检查= 0,pre-检查= 0
到期日:周四,1981年11月19日八时52分00秒格林尼治标准​​时间
 

这意味着客户端必须始终从HTTP服务器从它的本地缓存连接和加载的URL,从来没有。这也解释了为什么未知铬错误:-400 当您尝试加载页之后网络适配器关闭发生。 未知铬错误:-400 一般是指无法连接互联网由于某种原因,

还有就是你可以不用登录,并调整HTTP服务器设置什么。您可以使用以下URL检查你的缓存实现:

  http://stackoverflow.com/questions/14549638/webview-not-displaying-website-when-offline
 

响应头是:

  200 OK
......
最后一次修改:周三,2013年1月30日0时28分59秒格林尼治标准​​时间
变化: *
内容类型:text / html的;字符集= UTF-8
缓存控制:公共,最大年龄= 60
到期日:周三,2013年1月30日0时29分59秒格林尼治标准​​时间
 

如果有一个在您code没有其他问题,你的缓存实现应该工作。

I have an app that registers with GCM for push notifications. That code works fine and is not the source of my problem. Once registered, the app simply displays a website in a WebView. So far so good all this works if the device's network adapter is switched on.

If the network adapter is switched off then the webview should load from cache. This part is not working. I have followed the tutorial below and taken parts from it in a bit to save the website pages in a cache saved on the sdcard.

If i run the app the web site is displayed. If i then turn off the network adapter and visit the site, it will not display. I check the cache directory on the sdcard and parts of the site have been written to the cache.

Why doesn't the site load from cache when off-line?

Is it possible to keep the webpages it the cache until say the app is uninstalled or android decides otherwise?

tutorial

The tutorial shows you how to create a directory on the sdcard and write to it. The directories do exist but the webview is not restored from this cache in offline mode.

below is how i call the mainactivity that displays the webview.

Intent i = new Intent(getApplicationContext(), MainActivity.class);
                //i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                i.putExtra("name", "hardcoded client name");
                i.putExtra("email", "hardcoded email");
                startActivity(i);
                finish();

.

Here is the full MainActivity. You can ignore the first part as that's the code that handle the GCM push notification stuff, that all works. I need to know why the webview will not load from cache.

   import static com.bmi.bmitestapp.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.bmi.bmitestapp.CommonUtilities.EXTRA_MESSAGE;
import static com.bmi.bmitestapp.CommonUtilities.SENDER_ID;

import java.io.File;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;
import android.webkit.*;


import com.google.android.gcm.GCMRegistrar;

public class MainActivity extends Activity {
    private static final String TAG = MainActivity.class.getSimpleName();
    // label to display gcm messages
    TextView lblMessage;
    WebView webView;
    // Asyntask
    AsyncTask<Void, Void, Void> mRegisterTask;

    // Alert dialog manager
    AlertDialogManager alert = new AlertDialogManager();

    // Connection detector
    ConnectionDetector cd;

    public static String name;
    public static String email;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.e(TAG, "in onCreate in mainactivity");
        cd = new ConnectionDetector(getApplicationContext());

        // Check if Internet present
//        if (!cd.isConnectingToInternet()) {
//            // Internet Connection is not present
//            alert.showAlertDialog(MainActivity.this,
//                    "Internet Connection Error",
//                    "Please connect to working Internet connection", false);
//            // stop executing code by return
//            return;
//        }

        // Getting name, email from intent
        Intent i = getIntent();

        name = i.getStringExtra("name");
        email = i.getStringExtra("email");     

        // Make sure the device has the proper dependencies.
        GCMRegistrar.checkDevice(this);

        // Make sure the manifest was properly set - comment out this line
        // while developing the app, then uncomment it when it's ready.
        GCMRegistrar.checkManifest(this);

        lblMessage = (TextView) findViewById(R.id.lblMessage);

        registerReceiver(mHandleMessageReceiver, new IntentFilter(
                DISPLAY_MESSAGE_ACTION));

        // Get GCM registration id
        final String regId = GCMRegistrar.getRegistrationId(this);

        // Check if regid already presents
        if (regId.equals("")) {
            // Registration is not present, register now with GCM
            GCMRegistrar.register(this, SENDER_ID);
        } else {
            // Device is already registered on GCM
            if (GCMRegistrar.isRegisteredOnServer(this)) {
                // Skips registration.
                Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
            } else {
                // Try to register again, but not in the UI thread.
                // It's also necessary to cancel the thread onDestroy(),
                // hence the use of AsyncTask instead of a raw thread.
                final Context context = this;
                mRegisterTask = new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        // Register on our server
                        // On server creates a new user
                        ServerUtilities.register(context, name, email, regId);
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        mRegisterTask = null;
                    }

                };
                mRegisterTask.execute(null, null, null);
            }
        }

            webView = (WebView)findViewById(R.id.webView1);
            // Initialize the WebView
            webView.getSettings().setSupportZoom(true);
            webView.getSettings().setBuiltInZoomControls(true);
            webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
            webView.setScrollbarFadingEnabled(true);
            webView.getSettings().setLoadsImagesAutomatically(true);





            webView.getSettings().setDomStorageEnabled(true);

            // Set cache size to 8 mb by default. should be more than enough
            webView.getSettings().setAppCacheMaxSize(1024*1024*8);

            // This next one is crazy. It's the DEFAULT location for your app's cache
            // But it didn't work for me without this line.
            // UPDATE: no hardcoded path. Thanks to Kevin Hawkins
            String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
            Log.e(TAG, "appCachePath = " + appCachePath);
            webView.getSettings().setAppCachePath(appCachePath);
            webView.getSettings().setAllowFileAccess(true);
            webView.getSettings().setAppCacheEnabled(true);




            // Load the URLs inside the WebView, not in the external web browser
            webView.setWebViewClient(new WebViewClient());   

            if (savedInstanceState == null)
                        {



        if(isNetworkAvailable() == true){
            Log.e(TAG, "we have a network connection");
            webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

            webView.loadUrl("http://bmi.cubecore.co.uk");


        } else {
            Log.e(TAG, "we don't have a network connection");
            webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY);

            webView.loadUrl("http://bmi.cubecore.co.uk");
        }


                        } 

    }      //end of oncreate


    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }


    /**
     * Receiving push messages
     * */
    private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
            // Waking up mobile if it is sleeping
            WakeLocker.acquire(getApplicationContext());

            /**
             * Take appropriate action on this message
             * depending upon your app requirement
             * For now i am just displaying it on the screen
             * */

            // Showing received message
            lblMessage.append(newMessage + "\n");
            Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();

            // Releasing wake lock
            WakeLocker.release();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // Clear the cache (this clears the WebViews cache for the entire application)
        //webView.clearCache(false);

        if (mRegisterTask != null) {
            mRegisterTask.cancel(true);
        }
        try {
            unregisterReceiver(mHandleMessageReceiver);
            GCMRegistrar.onDestroy(this);
        } catch (Exception e) {
            Log.e("UnRegister Receiver Error", "> " + e.getMessage());
        }



    }



    @Override
    public void onBackPressed() {
        super.onBackPressed();


    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "in onResume in mainactivity");

    }



    @Override
    public File getCacheDir()
    {
        // NOTE: this method is used in Android 2.1
Log.e(TAG, "getcachedir");
        return getApplicationContext().getCacheDir();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);

        // Save the state of the WebView
        webView.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);

        // Restore the state of the WebView
        webView.restoreState(savedInstanceState);
    }

}

.

Here's the code from the tutorial above that writes to the sdcard.

package com.bmi.bmitestapp;

import java.io.File;

import android.app.Application;
import android.os.Environment;
import android.util.Log;

public class ApplicationExt extends Application
{
    private static final String TAG = ApplicationExt.class.getSimpleName();
    // NOTE: the content of this path will be deleted
    //       when the application is uninstalled (Android 2.2 and higher)
    protected File extStorageAppBasePath;

    protected File extStorageAppCachePath;

    @Override
    public void onCreate()
    {
        super.onCreate();
         Log.e(TAG, "inside appext");
        // Check if the external storage is writeable
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
        {

            // Retrieve the base path for the application in the external storage
            File externalStorageDir = Environment.getExternalStorageDirectory();

            if (externalStorageDir != null)
            {
                // {SD_PATH}/Android/data/com.devahead.androidwebviewcacheonsd
                extStorageAppBasePath = new File(externalStorageDir.getAbsolutePath() +
                    File.separator + "Android" + File.separator + "data" +
                    File.separator + getPackageName());
            }

            if (extStorageAppBasePath != null)
            {
                // {SD_PATH}/Android/data/com.devahead.androidwebviewcacheonsd/cache
                extStorageAppCachePath = new File(extStorageAppBasePath.getAbsolutePath() +
                    File.separator + "cache");

                boolean isCachePathAvailable = true;

                if (!extStorageAppCachePath.exists())
                {
                    // Create the cache path on the external storage
                    isCachePathAvailable = extStorageAppCachePath.mkdirs();
                }

                if (!isCachePathAvailable)
                {
                    // Unable to create the cache path
                    extStorageAppCachePath = null;
                }
            }
        }
    }

    @Override
    public File getCacheDir()
    {
        // NOTE: this method is used in Android 2.2 and higher

        if (extStorageAppCachePath != null)
        {
            // Use the external storage for the cache
            Log.e(TAG, "extStorageAppCachePath = " + extStorageAppCachePath);
            return extStorageAppCachePath;
        }
        else
        {
            // /data/data/com.devahead.androidwebviewcacheonsd/cache
            return super.getCacheDir();
        }
    }
}

I thought i'd include a little logging. This is the logging from a fresh install with the network adapter ON.

01-29 14:13:10.220: D/dalvikvm(16904): Late-enabling CheckJNI
01-29 14:13:10.470: E/ApplicationExt(16904): inside appext
01-29 14:13:10.720: E/RegisterActivity(16904): in onresume in registeractivity
01-29 14:13:10.880: D/libEGL(16904): loaded /system/lib/egl/libEGL_tegra.so
01-29 14:13:11.000: D/libEGL(16904): loaded /system/lib/egl/libGLESv1_CM_tegra.so
01-29 14:13:11.030: D/libEGL(16904): loaded /system/lib/egl/libGLESv2_tegra.so
01-29 14:13:11.070: D/OpenGLRenderer(16904): Enabling debug mode 0
01-29 14:13:18.390: E/ApplicationExt(16904): extStorageAppCachePath = /mnt/sdcard/Android/data/com.bmi.bmitestapp/cache
01-29 14:13:18.390: D/webview(16904): [InitTabEffectPivot] >> nScreenWidth = 720
01-29 14:13:18.390: D/webview(16904): [InitTabEffectPivot] >> nScreenHeight = 1280
01-29 14:13:18.390: D/SqliteDatabaseCpp(16904): Registering sqlite logging func: /data/data/com.bmi.bmitestapp/databases/webview.db
01-29 14:13:18.390: D/SqliteDatabaseCpp(16904): DB info: open db, path = /data/data/com.bmi.bmitestapp/databases , key = sefraes, flag = 6, cannot stat file, errno = 2, message = No such file or directory
01-29 14:13:18.400: E/MainActivity(16904): in onCreate in mainactivity
01-29 14:13:18.400: D/SqliteDatabaseCpp(16904): DB info: path = /data/data/com.bmi.bmitestapp/databases , key = sefraes, handle: 0x1f9a858, type: w, r/w: (0,1), mode: delete, disk free size: 1276 M
01-29 14:13:18.400: D/GCMRegistrar(16904): resetting backoff for com.bmi.bmitestapp
01-29 14:13:18.420: V/GCMRegistrar(16904): Registering app com.bmi.bmitestapp of senders 598080744593
01-29 14:13:18.430: E/ApplicationExt(16904): extStorageAppCachePath = /mnt/sdcard/Android/data/com.bmi.bmitestapp/cache
01-29 14:13:18.430: E/MainActivity(16904): appCachePath = /mnt/sdcard/Android/data/com.bmi.bmitestapp/cache
01-29 14:13:18.430: E/MainActivity(16904): we have a network connection
01-29 14:13:18.430: E/MainActivity(16904): in onResume in mainactivity
01-29 14:13:18.490: W/webcore(16904): java.lang.Throwable: EventHub.removeMessages(int what = 107) is not supported before the WebViewCore is set up.
01-29 14:13:18.490: W/webcore(16904):   at android.webkit.WebViewCore$EventHub.removeMessages(WebViewCore.java:1974)
01-29 14:13:18.490: W/webcore(16904):   at android.webkit.WebViewCore$EventHub.access$9100(WebViewCore.java:1008)
01-29 14:13:18.490: W/webcore(16904):   at android.webkit.WebViewCore.removeMessages(WebViewCore.java:2215)
01-29 14:13:18.490: W/webcore(16904):   at android.webkit.WebView.sendOurVisibleRect(WebView.java:3285)
01-29 14:13:18.490: W/webcore(16904):   at android.webkit.ZoomManager.setZoomScale(ZoomManager.java:772)
01-29 14:13:18.490: W/webcore(16904):   at android.webkit.ZoomManager.access$1900(ZoomManager.java:59)
01-29 14:13:18.490: W/webcore(16904):   at android.webkit.ZoomManager$PostScale.run(ZoomManager.java:1345)
01-29 14:13:18.490: W/webcore(16904):   at android.os.Handler.handleCallback(Handler.java:608)
01-29 14:13:18.490: W/webcore(16904):   at android.os.Handler.dispatchMessage(Handler.java:92)
01-29 14:13:18.490: W/webcore(16904):   at android.os.Looper.loop(Looper.java:156)
01-29 14:13:18.490: W/webcore(16904):   at android.app.ActivityThread.main(ActivityThread.java:5045)
01-29 14:13:18.490: W/webcore(16904):   at java.lang.reflect.Method.invokeNative(Native Method)
01-29 14:13:18.490: W/webcore(16904):   at java.lang.reflect.Method.invoke(Method.java:511)
01-29 14:13:18.490: W/webcore(16904):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-29 14:13:18.490: W/webcore(16904):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-29 14:13:18.490: W/webcore(16904):   at dalvik.system.NativeStart.main(Native Method)
01-29 14:13:18.500: W/webcore(16904): java.lang.Throwable: EventHub.removeMessages(int what = 105) is not supported before the WebViewCore is set up.
01-29 14:13:18.500: W/webcore(16904):   at android.webkit.WebViewCore$EventHub.removeMessages(WebViewCore.java:1974)
01-29 14:13:18.500: W/webcore(16904):   at android.webkit.WebViewCore$EventHub.access$9100(WebViewCore.java:1008)
01-29 14:13:18.500: W/webcore(16904):   at android.webkit.WebViewCore.removeMessages(WebViewCore.java:2215)
01-29 14:13:18.500: W/webcore(16904):   at android.webkit.WebView.sendViewSizeZoom(WebView.java:3520)
01-29 14:13:18.500: W/webcore(16904):   at android.webkit.ZoomManager.setZoomScale(ZoomManager.java:778)
01-29 14:13:18.500: W/webcore(16904):   at android.webkit.ZoomManager.access$1900(ZoomManager.java:59)
01-29 14:13:18.500: W/webcore(16904):   at android.webkit.ZoomManager$PostScale.run(ZoomManager.java:1345)
01-29 14:13:18.500: W/webcore(16904):   at android.os.Handler.handleCallback(Handler.java:608)
01-29 14:13:18.500: W/webcore(16904):   at android.os.Handler.dispatchMessage(Handler.java:92)
01-29 14:13:18.500: W/webcore(16904):   at android.os.Looper.loop(Looper.java:156)
01-29 14:13:18.500: W/webcore(16904):   at android.app.ActivityThread.main(ActivityThread.java:5045)
01-29 14:13:18.500: W/webcore(16904):   at java.lang.reflect.Method.invokeNative(Native Method)
01-29 14:13:18.500: W/webcore(16904):   at java.lang.reflect.Method.invoke(Method.java:511)
01-29 14:13:18.500: W/webcore(16904):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-29 14:13:18.500: W/webcore(16904):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-29 14:13:18.500: W/webcore(16904):   at dalvik.system.NativeStart.main(Native Method)
01-29 14:13:18.530: D/OpenGLRenderer(16904): Flushing caches (mode 0)
01-29 14:13:18.570: I/SqliteDatabaseCpp(16904): sqlite returned: error code = 1, msg = no such table: CacheGroups
01-29 14:13:18.570: I/SqliteDatabaseCpp(16904): sqlite returned: error code = 1, msg = no such table: Caches
01-29 14:13:18.570: I/SqliteDatabaseCpp(16904): sqlite returned: error code = 1, msg = no such table: Origins
01-29 14:13:18.570: I/SqliteDatabaseCpp(16904): sqlite returned: error code = 1, msg = no such table: DeletedCacheResources
01-29 14:13:18.850: E/ApplicationExt(16904): extStorageAppCachePath = /mnt/sdcard/Android/data/com.bmi.bmitestapp/cache
01-29 14:13:19.330: I/PRIME(16904): <CallBackProxy> Send to WebViewClient.
01-29 14:13:19.370: V/GCMBroadcastReceiver(16904): onReceive: com.google.android.c2dm.intent.REGISTRATION
01-29 14:13:19.370: V/GCMBroadcastReceiver(16904): GCM IntentService class: com.bmi.bmitestapp.GCMIntentService
01-29 14:13:19.370: V/GCMBaseIntentService(16904): Acquiring wakelock
01-29 14:13:19.460: V/GCMBaseIntentService(16904): Intent service name: GCMIntentService-598080744593-1
01-29 14:13:19.470: E/GCMRegistrar(16904): internal error: retry receiver class not set yet
01-29 14:13:19.480: V/GCMRegistrar(16904): Registering receiver
01-29 14:13:19.480: D/GCMBaseIntentService(16904): handleRegistration: registrationId = APA91bFytZvnkmsEVHSnw5VRxIwfPRmPsSRVrgRNRa5ww3oqCfnLEZMaBBNtQtlZoK4RD4VQXfAfKDsQUa53PwQBH_rwuI_gEEdHQhxadpBVmJ7L3Dxy90Bzryg_aCWx20-cdZ32cbiiaGR3zUMjpqZizYQbnARN4w, error = null, unregistered = null
01-29 14:13:19.480: D/GCMRegistrar(16904): resetting backoff for com.bmi.bmitestapp
01-29 14:13:19.480: V/GCMRegistrar(16904): Saving regId on app version 1
01-29 14:13:19.490: I/GCMIntentService(16904): Device registered: regId = APA91bFytZvnkmsEVHSnw5VRxIwfPRmPsSRVrgRNRa5ww3oqCfnLEZMaBBNtQtlZoK4RD4VQXfAfKDsQUa53PwQBH_rwuI_gEEdHQhxadpBVmJ7L3Dxy90Bzryg_aCWx20-cdZ32cbiiaGR3zUMjpqZizYQbnARN4w
01-29 14:13:19.490: D/NAME(16904): hardcoded client name
01-29 14:13:19.490: I/bmi GCM(16904): registering device (regId = APA91bFytZvnkmsEVHSnw5VRxIwfPRmPsSRVrgRNRa5ww3oqCfnLEZMaBBNtQtlZoK4RD4VQXfAfKDsQUa53PwQBH_rwuI_gEEdHQhxadpBVmJ7L3Dxy90Bzryg_aCWx20-cdZ32cbiiaGR3zUMjpqZizYQbnARN4w)
01-29 14:13:19.490: D/bmi GCM(16904): Attempt #1 to register
01-29 14:13:19.500: V/bmi GCM(16904): Posting 'email=hardcoded email&regId=APA91bFytZvnkmsEVHSnw5VRxIwfPRmPsSRVrgRNRa5ww3oqCfnLEZMaBBNtQtlZoK4RD4VQXfAfKDsQUa53PwQBH_rwuI_gEEdHQhxadpBVmJ7L3Dxy90Bzryg_aCWx20-cdZ32cbiiaGR3zUMjpqZizYQbnARN4w&name=hardcoded client name' to http://mobilewebexpert.co.uk/pushtest/register.php
01-29 14:13:19.500: E/URL(16904): > http://mobilewebexpert.co.uk/pushtest/register.php
01-29 14:13:20.610: V/GCMRegistrar(16904): Setting registeredOnServer status as true until 2013-02-05 14:13:20.617
01-29 14:13:20.620: V/GCMBaseIntentService(16904): Releasing wakelock
01-29 14:13:21.470: D/skia(16904): notifyPluginsOnFrameLoad not postponed
01-29 14:13:21.570: D/SQLiteDatabase(16904): Create pool connection
01-29 14:13:21.570: D/SqliteDatabaseCpp(16904): DB info: open db, path = /data/data/com.bmi.bmitestapp/databases , key = sefraes, flag = 1, file size = 12288
01-29 14:13:21.570: D/SqliteDatabaseCpp(16904): DB info: path = /data/data/com.bmi.bmitestapp/databases , key = sefraes, handle: 0x2797350, type: r, r/w: (1,1), mode: wal, disk free size: 1276 M

.

This is the logging after i have turned off the network adapter.

01-29 14:16:57.080: E/RegisterActivity(16904): in onresume in registeractivity
01-29 14:17:03.490: D/webview(16904): [InitTabEffectPivot] >> nScreenWidth = 720
01-29 14:17:03.490: D/webview(16904): [InitTabEffectPivot] >> nScreenHeight = 1280
01-29 14:17:03.490: E/MainActivity(16904): in onCreate in mainactivity
01-29 14:17:03.490: V/GCMRegistrar(16904): Is registered on server: true
01-29 14:17:03.500: E/ApplicationExt(16904): extStorageAppCachePath = /mnt/sdcard/Android/data/com.bmi.bmitestapp/cache
01-29 14:17:03.500: E/MainActivity(16904): appCachePath = /mnt/sdcard/Android/data/com.bmi.bmitestapp/cache
01-29 14:17:03.500: E/MainActivity(16904): we don't have a network connection
01-29 14:17:03.500: E/MainActivity(16904): in onResume in mainactivity
01-29 14:17:03.500: D/chromium(16904): Unknown chromium error: -400
01-29 14:17:03.540: D/skia(16904): notifyPluginsOnFrameLoad not postponed
01-29 14:17:03.580: D/OpenGLRenderer(16904): Flushing caches (mode 0)

One thing i've noticed, it might be nothing, but registeractivity is the activity that calls MainActivity. RegisterActivity just has a button that fires an Intent for MainActivity. After the network adapter is off i have to press the button on registerAcivity, which calls onCreate in MainActivity. It is like it's a new instance of MainActivity?? Could this be effecting the caching of the webview. Effectively the onDestroy of the main activity must have been called along the way.

Also another thing has caught my attention.

01-29 14:17:03.580: D/OpenGLRenderer(16904): Flushing caches (mode 0) 
解决方案

For that particular URL http://bmi.cubecore.co.uk, your WebView's caching is prohibited by that http server, see the response header Cache-Control:

200 OK
... ...
Pragma: no-cache
Server: Apache/2.2.3 (CentOS)
Content-Type: text/html; charset=utf-8
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Expires: Thu, 19 Nov 1981 08:52:00 GMT

This means the client must always connect and load the URL from http server, never from its local cache. That also explained why Unknown chromium error: -400 occurred when you try to load the page after network adapter is switched off. Unknown chromium error: -400 generally means failed to connect internet for some reason.

There is nothing you can do without login and adjust the http server settings. You can use the following URL exam your cache implementation:

http://stackoverflow.com/questions/14549638/webview-not-displaying-website-when-offline

The response header is:

200 OK
... ...
Last-Modified: Wed, 30 Jan 2013 00:28:59 GMT
Vary: *
Content-Type: text/html; charset=utf-8
Cache-Control: public, max-age=60
Expires: Wed, 30 Jan 2013 00:29:59 GMT

If there is no other issue in your code, your cache implementation should work.

这篇关于web视图不显示网站时,离线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 05:16