user3810679
user3810679

Reputation: 79

How to refresh token after particular time?

I am working in an application in which I need to refresh my token after every 60 minutes. I have created a service which runs in the background. However, the problem I am facing is, when the phone goes to sleep mode, my service gets stopped and hence I am unable to refresh my token. I am getting this problem mostly in OREO & PIE.

public class InActivityTimer extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
        mService = APIUtils_AI.getSOService();
        mService2 = APIUtils_AI.getSOServiceAI();
        utils = new Utils();
        receiver = new BroadcastTokenCheck();
        filter = new IntentFilter(COUNTDOWN_BR);
        registerReceiver(receiver, filter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        cdt = new CountDownTimer(15000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
                if(millisUntilFinished<8000&&millisUntilFinished>5000){
                    if(!isSecond){
                        Log.i("", "Running: ");
                        refreshToken();//Refresh Token API
                        cdt.cancel();
                        cdt.start();
                    }
                }
            }

            @Override
            public void onFinish() {
                Intent intent = new Intent(COUNTDOWN_BR);
                intent.putExtra("VALUE","startService");
                sendBroadcast(intent);
                //stopSelf();
                Log.i("", "Timer finished");
            }
        }.start();

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(receiver);
        Log.e("Service Status: ","Stopped");
        cdt.cancel();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

Upvotes: 0

Views: 3097

Answers (2)

Shobhit Puri
Shobhit Puri

Reputation: 26007

Here is my 2 cents.

I assume you are calling refreshToken() to fetch a new token from the server, so that when you make the next REST call, you can use this valid token.

Maybe instead of continuously running a service in background, refreshing tokens and consuming the resources, even though user might not be using your app actively, you can do the following:

  • Keep a local flag in SharedPreference, where you keep record of how long it has been since you made the last call to refresh token. Or you can save the timestamp till the current token is valid.
  • Before making the REST call, you can check if your current token is valid or not by checking your shared preference.
  • If its not valid, fetch a new token and then when you receive the response, use that new token to make the initial call. Also persist the token that you received and update the SharedPreference flag.

Note: in case you are using Retrofit for REST calls, you can use something like Interceptor where you can do the above check. Something like this answer: Answer on "Refreshing OAuth token using Retrofit without modifying all calls"

Upvotes: 2

Reaz Murshed
Reaz Murshed

Reputation: 24211

My suggestion is to refresh the token when necessary. From my understanding, the token is required to authenticate an API call in a server application. When the API returns unauthorized or 401 error status, you might consider refreshing the token in that case.

Android 8.0 put some limitations to background services which are described briefly in their developer's documentation. If you really need to refresh your token after every 60 minutes, then you might consider using JobScheduler which is suggested in their documentation.

However, I want to recommend to refresh your token in the onResume function of your launcher activity if 60 min has elapsed after the last refresh. The situation may vary based on your server-side implementation though.

Hope that helps!

Upvotes: 3

Related Questions