-
Notifications
You must be signed in to change notification settings - Fork 61
/
AsyncLoginUpdater.java
46 lines (37 loc) · 1.48 KB
/
AsyncLoginUpdater.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.airlocksoftware.hackernews.loader;
import java.util.Calendar;
import org.apache.commons.lang3.StringUtils;
import android.content.Context;
import android.os.AsyncTask;
import com.airlocksoftware.hackernews.data.LoginManager;
import com.airlocksoftware.hackernews.data.UserPrefs;
/**
* Responsible for updating the user cookie in the background. It gets started by the MainActivity, and should run once
* a week.
**/
public class AsyncLoginUpdater extends AsyncTask<Void, Void, Void> {
Context mApplicationContext;
public static final long COOKIE_EXPIRATION = 1000 * 60 * 60 * 24 * 7; // one weeks
/** Be sure to use an Application context in case of rotation happening while this is running **/
public AsyncLoginUpdater(Context applicationContext) {
mApplicationContext = applicationContext;
}
@Override
protected Void doInBackground(Void... arg0) {
UserPrefs prefs = new UserPrefs(mApplicationContext);
long timestamp = prefs.getCookieTimestamp();
String username = prefs.getUsername();
String password = prefs.getPassword();
long currentTime = Calendar.getInstance()
.getTimeInMillis();
boolean expired = currentTime - timestamp > COOKIE_EXPIRATION;
if (expired && StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
String newCookie = LoginManager.login(username, password);
if (newCookie != null) {
// saves new user cookie and updates the timestamp
prefs.saveUserCookie(newCookie);
}
}
return null;
}
}