aProgger
aProgger

Reputation: 871

Android WebView sync cookies on older apis

I am using CookieSyncManager to sync cookies. I followed the guide from Android Documentation. Created instance in oncreate, stopped syncing in onPause, resumed in onResume. Additionally I fire

CookieSyncManager.getInstance().sync();

at the end of onPageFinished.

Since API21 I got a deprecated warning and according to the Android Documentation, we should use

CookieManager.getInstance().flush();

only now to fire a synchronisation.

I tried already

if (android.os.Build.VERSION.SDK_INT >= 21) CookieManager.getInstance().flush();
else CookieSyncManager.getInstance().sync();

but it gives me an error of having API15 as minimum.

I do not like the idea of ignoring a deprecation but what to do with API15?

Edit:

From comment (not sure if I understood it right):

@Override
public void onPageFinished(WebView view, String url) {
  
  if (android.os.Build.VERSION.SDK_INT >= 21) flushCookies();
  else syncCookies();
}

@TargetApi(21) //add this
private void flushCookies() {

  CookieManager.getInstance().flush();
}

private void syncCookies() {

  CookieSyncManager.getInstance().sync();
}

Solves the lint hint I thougt it was an error.

Upvotes: 2

Views: 5266

Answers (2)

Stoycho Andreev
Stoycho Andreev

Reputation: 6283

Actually you can do it by different way:

@SuppressWarnings("deprecation")
public static void loadCookies() {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        CookieManager.getInstance().flush();
    } else {
        CookieSyncManager.getInstance().sync();
    }
}

Call this method in your onPageFinished(WebView view, String url) This code looks much clean and you shall not see your method to looks like deprecated.

Upvotes: 2

aProgger
aProgger

Reputation: 871

based on Selvin's comment:

@Override
public void onPageFinished(WebView view, String url) {

  if (android.os.Build.VERSION.SDK_INT >= 21) flushCookies();
  else CookieSyncManager.getInstance().sync();
}

@TargetApi(21)
private void flushCookies() {

  CookieManager.getInstance().flush();
}

did the trick. Thank you again.

Upvotes: 0

Related Questions