Fetch a new access token in onCreate method of MainActivity when the old access token is about to expire, specifically, to expire within the next 5 minutes or is already expired to avoid refreshing the access token many times by other queries later.

This commit is contained in:
Alex Ning 2018-08-05 14:26:01 +08:00
parent c6026e5659
commit f2eb18749c
7 changed files with 91 additions and 22 deletions

View File

@ -14,6 +14,7 @@ import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
@ -39,15 +40,16 @@ class AcquireAccessToken {
if(mContext != null) {
mAcquireAccessTokenListener = acquireAccessTokenListener;
final String refreshToken = mContext.getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE).getString(SharedPreferencesUtils.REFRESH_TOKEN_KEY, "");
final SharedPreferences.Editor editor = mContext.getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE).edit();
StringRequest newTokenRequest = new StringRequest(Request.Method.POST, RedditUtils.ACQUIRE_ACCESS_TOKEN_URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String newAccessToken = jsonObject.getString(RedditUtils.ACCESS_TOKEN_KEY);
SharedPreferences.Editor editor = mContext.getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE).edit();
int expireIn = jsonObject.getInt(RedditUtils.EXPIRES_IN_KEY);
editor.putString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, newAccessToken);
editor.putInt(SharedPreferencesUtils.ACCESS_TOKEN_EXPIRE_INTERVAL_KEY, expireIn);
editor.apply();
Log.i("access token", newAccessToken);
@ -81,6 +83,11 @@ class AcquireAccessToken {
}
};
newTokenRequest.setTag(AcquireAccessToken.class);
long queryAccessTokenTime = Calendar.getInstance().getTimeInMillis();
editor.putLong(SharedPreferencesUtils.QUERY_ACCESS_TOKEN_TIME_KEY, queryAccessTokenTime);
editor.apply();
refreshQueue.add(newTokenRequest);
}
}

View File

@ -26,6 +26,7 @@ import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
@ -50,6 +51,7 @@ public class MainActivity extends AppCompatActivity {
private String mBannerImageUrl;
private String mKarma;
private boolean mFetchUserInfoSuccess;
private boolean mIsInserting;
private SubscribedSubredditViewModel mSubscribedSubredditViewModel;
private SubscribedUserViewModel mSubscribedUserViewModel;
@ -67,6 +69,25 @@ public class MainActivity extends AppCompatActivity {
drawer.addDrawerListener(toggle);
toggle.syncState();
Calendar now = Calendar.getInstance();
Calendar queryAccessTokenTime = Calendar.getInstance();
queryAccessTokenTime.setTimeInMillis(getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE)
.getLong(SharedPreferencesUtils.QUERY_ACCESS_TOKEN_TIME_KEY, 0));
int interval = getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE)
.getInt(SharedPreferencesUtils.ACCESS_TOKEN_EXPIRE_INTERVAL_KEY, 0);
queryAccessTokenTime.add(Calendar.SECOND, interval - 300);
if(now.after(queryAccessTokenTime)) {
new AcquireAccessToken(this).refreshAccessToken(Volley.newRequestQueue(this),
new AcquireAccessToken.AcquireAccessTokenListener() {
@Override
public void onAcquireAccessTokenSuccess() {}
@Override
public void onAcquireAccessTokenFail() {}
});
}
View header = findViewById(R.id.nav_header_main_activity);
mNameTextView = header.findViewById(R.id.name_text_view_nav_header_main);
mKarmaTextView = header.findViewById(R.id.karma_text_view_nav_header_main);
@ -164,7 +185,7 @@ public class MainActivity extends AppCompatActivity {
mSubscribedSubredditViewModel.getAllSubscribedSubreddits().observe(this, new Observer<List<SubscribedSubredditData>>() {
@Override
public void onChanged(@Nullable final List<SubscribedSubredditData> subscribedSubredditData) {
// Update the cached copy of the words in the adapter.
if(!mIsInserting) {
if(subscribedSubredditData == null || subscribedSubredditData.size() == 0) {
subscriptionsLabelTextView.setVisibility(View.GONE);
} else {
@ -173,6 +194,7 @@ public class MainActivity extends AppCompatActivity {
subredditadapter.setSubscribedSubreddits(subscribedSubredditData);
}
}
});
final SubscribedUserRecyclerViewAdapter userAdapter = new SubscribedUserRecyclerViewAdapter(this);
@ -181,7 +203,7 @@ public class MainActivity extends AppCompatActivity {
mSubscribedUserViewModel.getAllSubscribedUsers().observe(this, new Observer<List<SubscribedUserData>>() {
@Override
public void onChanged(@Nullable final List<SubscribedUserData> subscribedUserData) {
// Update the cached copy of the words in the adapter.
if(!mIsInserting) {
if(subscribedUserData == null || subscribedUserData.size() == 0) {
followingLabelTextView.setVisibility(View.GONE);
} else {
@ -189,6 +211,7 @@ public class MainActivity extends AppCompatActivity {
}
userAdapter.setSubscribedUsers(subscribedUserData);
}
}
});
new FetchSubscribedThing(this, Volley.newRequestQueue(this), new ArrayList<SubscribedSubredditData>(),
@ -197,11 +220,18 @@ public class MainActivity extends AppCompatActivity {
@Override
public void onFetchSubscribedSubredditsSuccess(ArrayList<SubscribedSubredditData> subscribedSubredditData,
ArrayList<SubscribedUserData> subscribedUserData) {
mIsInserting = true;
new InsertSubscribedThingsAsyncTask(
SubscribedSubredditRoomDatabase.getDatabase(MainActivity.this),
SubscribedUserRoomDatabase.getDatabase(MainActivity.this),
subscribedSubredditData,
subscribedUserData).execute();
subscribedUserData,
new InsertSubscribedThingsAsyncTask.InsertSubscribedThingListener() {
@Override
public void insertSuccess() {
mIsInserting = false;
}
}).execute();
}
@Override
@ -252,19 +282,26 @@ public class MainActivity extends AppCompatActivity {
private static class InsertSubscribedThingsAsyncTask extends AsyncTask<Void, Void, Void> {
interface InsertSubscribedThingListener {
void insertSuccess();
}
private final SubscribedSubredditDao mSubredditDao;
private final SubscribedUserDao mUserDao;
private List<SubscribedSubredditData> subscribedSubredditData;
private List<SubscribedUserData> subscribedUserData;
private InsertSubscribedThingListener insertSubscribedThingListener;
InsertSubscribedThingsAsyncTask(SubscribedSubredditRoomDatabase subredditDb,
SubscribedUserRoomDatabase userDb,
List<SubscribedSubredditData> subscribedSubredditData,
List<SubscribedUserData> subscribedUserData) {
List<SubscribedUserData> subscribedUserData,
InsertSubscribedThingListener insertSubscribedThingListener) {
mSubredditDao = subredditDb.subscribedSubredditDao();
mUserDao = userDb.subscribedUserDao();
this.subscribedSubredditData = subscribedSubredditData;
this.subscribedUserData = subscribedUserData;
this.insertSubscribedThingListener = insertSubscribedThingListener;
}
@Override
@ -277,5 +314,10 @@ public class MainActivity extends AppCompatActivity {
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
insertSubscribedThingListener.insertSuccess();
}
}
}

View File

@ -34,6 +34,7 @@ class RedditUtils {
static final String SCOPE_KEY = "scope";
static final String SCOPE = "identity edit flair history modconfig modflair modlog modposts modwiki mysubreddits privatemessages read report save submit subscribe vote wikiedit wikiread";
static final String ACCESS_TOKEN_KEY = "access_token";
static final String EXPIRES_IN_KEY = "expires_in";
static final String AUTHORIZATION_KEY = "Authorization";
static final String AUTHORIZATION_BASE = "bearer ";

View File

@ -11,7 +11,7 @@ class SharedPreferencesUtils {
static final String ACCESS_TOKEN_KEY = "accessToken";
static final String REFRESH_TOKEN_KEY = "refreshToken";
static final String QUERY_ACCESS_TOKEN_TIME_KEY = "queryAccessTokenTime";
static final String ACCESS_TOKEN_EXPIRE_TIME_KEY = "accessTokenExpireTime";
static final String ACCESS_TOKEN_EXPIRE_INTERVAL_KEY = "accessTokenExpireInterval";
static final String MODHASH_KEY = "modhash";
static final String USER_KEY = "user";
static final String PROFILE_IMAGE_URL_KEY = "profileImageUrl";

View File

@ -9,6 +9,8 @@ import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
@ -34,7 +36,11 @@ public class ViewSubredditDetailActivity extends AppCompatActivity {
setSupportActionBar(toolbar);
String id = getIntent().getExtras().getString(EXTRA_SUBREDDIT_ID);
final String subredditName = getIntent().getExtras().getString(EXTRA_SUBREDDIT_NAME);
String subredditName = getIntent().getExtras().getString(EXTRA_SUBREDDIT_NAME);
final String title = "r/" + subredditName;
setTitle(title);
final CollapsingToolbarLayout collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar_layout_view_subreddit_detail_activity);
AppBarLayout appBarLayout = findViewById(R.id.app_bar_layout_view_subreddit_detail_activity);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
@ -47,7 +53,8 @@ public class ViewSubredditDetailActivity extends AppCompatActivity {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
collapsingToolbarLayout.setTitle(subredditName);
Log.i("asfasdf", "asdfasdf");
collapsingToolbarLayout.setTitle(title);
isShow = true;
} else if(isShow) {
collapsingToolbarLayout.setTitle(" ");//carefull there should a space between double quote otherwise it wont work
@ -114,6 +121,16 @@ public class ViewSubredditDetailActivity extends AppCompatActivity {
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return false;
}
private static class InsertSubredditDataAsyncTask extends AsyncTask<Void, Void, Void> {
private final SubredditDao mSubredditDao;

View File

@ -82,6 +82,7 @@
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_alignParentEnd="true"
android:layout_toStartOf="@id/subscriber_count_text_view_view_subreddit_detail_activity"
android:textColor="@android:color/black" />
</RelativeLayout>
@ -102,9 +103,11 @@
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="@style/AppTheme.PopupOverlay" />
app:popupTheme="@style/AppTheme.PopupOverlay"
app:navigationIcon="?attr/homeAsUpIndicator" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_view_subreddit_detail" />

View File

@ -19,7 +19,6 @@
<string name="profile">Profile</string>
<string name="following">Following</string>
<string name="subscriptions">Subscriptions</string>
<string name="title_activity_view_subreddit_detail">ViewSubredditDetailActivity</string>
<string name="subscribers_number_detail">Subscribers: %1$d</string>
<string name="online_subscribers_number_detail">Online: %1$d</string>
<string name="large_text">