How to work with new classes while maintaining backward compatibility in Android?

I need to use the CookieManager class for devices with version 9 or higher. My code looks like this:

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; } } 

When I run this on emulator 2.2; I have this error log;

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

When I need a CookieManager, I call this method with the os version check;

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

So, in my application, if version 2.2 or lower; this method is never called. My question is: why am I seeing this error log?

+4
source share
1 answer

I can replicate this on emulator 2.2 if I create an instance of HttpUtils in the calling activity code outside of the SDK check. For instance:

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

If NOT happening, if I instead call the static method directly:

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

If you have other non-static things in your HttpUtils class, you will have to move the CookieManager parts to another helper class and just call it statically ... or create an instance of HtppUtils after checking the SDK:

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

Source: https://habr.com/ru/post/1434375/


All Articles