You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio编译报错:无法找到WebSettings的AppCache相关方法

问题原因

这三个编译错误是因为setAppCacheMaxSize()、setAppCachePath()、setAppCacheEnabled()这三个方法在Android API 29(Android 10)及以上版本的WebSettings类中已被移除。Android从API 29开始,WebView的缓存策略改为系统自动管理,不再允许开发者手动指定缓存路径和大小。

解决方案

直接移除这三个过时的方法调用即可,WebView会自动处理缓存相关逻辑。如果需要兼容低版本(API 29以下),可以通过API版本判断来保留旧逻辑。

修改后的代码

public void initWebView() {
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setDefaultTextEncodingName("utf-8");
    // 替换已废弃的setPluginState方法
    webView.getSettings().setPluginEnabled(true);

    if (!isNetworkAvailable(mContext)) {
        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    }
}

兼容低版本的写法(可选)

如果需要支持API 29以下的设备,可以添加版本判断:

public void initWebView() {
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setDefaultTextEncodingName("utf-8");
    
    // 兼容API 29以下版本的缓存配置
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
        webView.getSettings().setAppCacheMaxSize(AppConstant.SITE_CACHE_SIZE);
        webView.getSettings().setAppCachePath(mContext.getCacheDir().getAbsolutePath());
        webView.getSettings().setAppCacheEnabled(true);
    }

    // 兼容不同版本的插件配置
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        webView.getSettings().setPluginEnabled(true);
    } else {
        webView.getSettings().setPluginState(WebSettings.PluginState.ON);
    }

    if (!isNetworkAvailable(mContext)) {
        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    }
}
额外说明
  • 代码中原有的setPluginState()方法在API 21已废弃,建议替换为setPluginEnabled(boolean),上述代码已做对应处理。
  • WebView的setCacheMode()方法已经可以满足大部分缓存场景需求,无需手动配置缓存路径和大小。

内容的提问来源于stack exchange,提问作者GoLiPeKa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 04:36:18