【问题标题】:How to work with new classes while being backward compatible in android?如何在 android 中向后兼容的同时使用新类?
【发布时间】:2012-09-15 15:17:20
【问题描述】:

我需要为 9 或更高版本的设备使用 CookieManager 类。我的代码看起来像这样;

public class HttpUtils {
private static CookieManager cookie_manager = null;

@TargetApi(9)
    public static CookieManager getCookieManager() {
        if (cookie_manager == null) {
            cookie_manager = new CookieManager();
            CookieHandler.setDefault(cookie_manager);
        }
        return cookie_manager;
    }
}

当我在 2.2 模拟器上运行它时;我有这个错误日志;

Could not find class 'java.net.CookieManager', referenced from method com.application.utils.HttpUtils.getCookieManager

当我需要 CookieManager 时,我会通过检查操作系统版本来调用此方法;

if (Build.VERSION.SDK_INT >= 9)
  ...

所以;如果版本为 2.2 或更低,则在我的应用中;这个方法永远不会被调用。我的问题是为什么我会看到这个错误日志?

【问题讨论】:

  • 我从你的代码中删除了@TargetApi(9) 并在 2.1 模拟器上运行它,它没有任何错误。
  • @hasanghaforian;它不会抛出异常,但是我提到了这个错误日志。你看到了吗?您是调试应用程序还是只是运行它?
  • 我在logcat中调试它没有错误。

标签: java android backwards-compatibility


【解决方案1】:

如果我在 SDK 检查之外的调用 Activity 的代码中创建 HttpUtils 实例,我可以在 2.2 模拟器上复制它。例如:

HttpUtils utils = new HttpUtils();

if (Build.VERSION.SDK_INT >= 9)
{
    Object test = utils.getCookieManager();
}

如果我直接调用静态方法则不会发生:

if (Build.VERSION.SDK_INT >= 9)
{
    Object test = HttpUtils.getCookieManager();
}

如果您的 HttpUtils 类中有其他非静态内容,则必须将 CookieManager 部分移动到不同的帮助程序类,并且仅静态调用它...或在您的 SDK 检查后实例化 HtppUtils:

    if (Build.VERSION.SDK_INT >= 9)
    {
        HttpUtils utils = new HttpUtils();
        Object test = utils.getCookieManager();
    }

【讨论】:

    猜你喜欢
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 2011-02-09
    • 1970-01-01
    • 2012-08-23
    • 2019-01-13
    • 1970-01-01
    相关资源
    最近更新 更多