在android studio webview中关闭应用程序时保留localstorage数据

时间:2018-01-22 20:19:57

标签: javascript android html5 android-studio webview

我使用android studio从我的网站制作应用程序,我真的需要localstorage,但每次关闭应用程序时它都会完全删除。我该如何解决?

<uses-permission android:name="android.permission.INTERNET" />

我使用此代码启用javascript和localstorage:

 myWebView = (WebView)findViewById(R.id.webView);
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.getSettings().setDomStorageEnabled(true);
        myWebView.getSettings().setDatabaseEnabled(true);

我已经看到其他人提出同样的问题并且我使用了这个答案:

 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            myWebView.getSettings().setDatabasePath("/data/data/" + myWebView.getContext().getPackageName() + "/databases/");
        }

但它表示已弃用,但仍然无效(每次重新启动应用时都会删除localstorage)。

请帮我解决这个问题,我希望保存本地存储!

2 个答案:

答案 0 :(得分:0)

不太了解你的问题,但试着补充一下:

CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);

String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
myWebView.setAllowFileAccess(true);
myWebView.setAppCachePath(appCachePath);


<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

答案 1 :(得分:0)

我设法在一个使用WebView的应用程序中将音频文件缓存在本地存储中。这意味着音频文件将被截取,然后在高速缓存中不可用时将其下载,然后从高速缓存中提供。缓存可以在Android 10上重启的手机中幸存下来。

这些是我用于WebView的设置:

@SuppressLint("SetJavaScriptEnabled")
public static void setupWebview(WebView webView) {
    WebSettings settings = webView.getSettings();
    settings.setLoadWithOverviewMode(true);
    settings.setUseWideViewPort(true);
    settings.setAllowFileAccess(true);
    settings.setAllowContentAccess(true);
    settings.setAllowFileAccessFromFileURLs(true);
    settings.setAllowUniversalAccessFromFileURLs(true);
    settings.setBlockNetworkImage(false);
    settings.setBlockNetworkLoads(false);
    settings.setLoadsImagesAutomatically(true);
    settings.setMediaPlaybackRequiresUserGesture(false);
    settings.setDomStorageEnabled(true);
    settings.setLoadWithOverviewMode(true);
    settings.setJavaScriptEnabled(true);
    settings.setAllowUniversalAccessFromFileURLs(true);
    settings.setDatabaseEnabled(true);
    settings.setAppCacheEnabled(true);
    settings.setAppCachePath("/beezone");
}

我对相同的WebClient使用了自定义的WebView

因此,自定义WebClient基本上是这样的:

    mWebView.setWebViewClient(new WebViewClient() {

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Nullable
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            return cacheM4a(request, context);
        }

        @Nullable
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            return cacheM4a(Uri.parse(url), context);
        }
    });

方法cacheM4a的相关代码如下:

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Nullable
public static WebResourceResponse cacheM4a(WebResourceRequest request, Context context) {
    Uri source = request.getUrl();
    return cacheM4a(source, context);
}

@Nullable
public static WebResourceResponse cacheM4a(Uri source, Context context) {
    String sourceStr = source.toString();
    if (sourceStr.endsWith(CacheHelper.MAIN_AUDIO_FORMAT)) {
        String language = LanguageHelper.INSTANCE.getLanguage();
        String absolutePath = context.getCacheDir().getAbsolutePath();
        String langPath = String.format("%s/%s", absolutePath, language);
        boolean folderExists = createLanguageCachePath(langPath);
        if(!folderExists) {
            try {
                return new WebResourceResponse("audio/mp4", "binary", new URL(sourceStr).openStream());
            } catch (IOException e) {
                Log.e(TAG, "Failed to read directly from the web", e);
                return null;
            }
        }
        String targetPath = String.format("%s/%s", langPath, source.getLastPathSegment());
        File file = new File(targetPath);
        if (!file.exists()) {
            if (saveToCache(sourceStr, targetPath)) return null;
        }
        // Always read from cache.
        try  {
            FileInputStream fis = new FileInputStream(new File(targetPath));
            WebResourceResponse response = new WebResourceResponse("audio/mp4", "binary", fis);
            return response;
        } catch (IOException e) {
            Log.e(TAG, "Failed to read cache", e);
            return null;
        }
    }
    return null;
}

private static boolean saveToCache(String sourceStr, String targetPath) {
    // File is not present in cache and thus needs to be downloaded
    try (InputStream in = new URL(sourceStr).openStream();
         FileOutputStream fos = new FileOutputStream(new File(targetPath))) {
        ByteStreams.copy(in, fos);
    } catch (IOException e) {
        Log.e(TAG, "Failed to save in cache", e);
        return true;
    }
    return false;
}

private static boolean createLanguageCachePath(String langPath) {
    File langPathFile = new File(langPath);
    if(!langPathFile.exists()) {
        if(!langPathFile.mkdirs()) {
            Log.e(TAG, String.format("Could not create %s", langPathFile));
            return false;
        };
    }
    return true;
}

这些是我使用的权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />