4

我需要为 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 或更低,则在我的应用中;这个方法永远不会被调用。我的问题是为什么我会看到这个错误日志?

4

1 回答 1

0

如果我在 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();
    }
于 2012-09-24T19:30:47.183 回答