AndroidPub
Published in

AndroidPub

How We Do Automatic Token Refreshing using Android’s New Work Manager

Rolling with the new black…

Photo by Suika Ibuki on Unsplash

What was the job to be done?

Behold, WorkManager

Preparing the token refresh job

class RefreshTokenWorker : Worker() {
override fun doWork(): Result {
/** Initializing credentials manager code goes here **/
val existingTokenId = credentialsManager.getToken().id val authToken = try {
credentialsManager
.issueToken()
.blockingGet()
} catch (exception: Exception) {
return Result.RETRY
}
credentialsManager.saveToken(authToken) try {
credentialsManager
.revokeTokens(listOf(existingTokenId))
.blockingGet()
} catch (exception: Exception) {
return Result.SUCCESS
}
return Result.SUCCESS
}
}

Scheduling the job

uniqueWorkName = "${getApplicationId()}:refresh-token-work"
fun startPeriodicRefreshTokenTask() {
val workConstraints = Constraints
.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val applicationData = Data.Builder()
.putString(Keys.APP_ID, getApplicationId())
.putString(Keys.LOGGING_LEVEL, mitterConfig.loggingLevel.toString())
.build()
val periodicRefreshTokenWork = PeriodicWorkRequest.Builder(
RefreshTokenWorker::class.java,
1,
TimeUnit.HOURS
).setConstraints(workConstraints)
.setInputData(applicationData)
.build()
WorkManager.getInstance()
?.enqueueUniquePeriodicWork(
uniqueWorkName,
ExistingPeriodicWorkPolicy.REPLACE,
periodicRefreshTokenWork
)
}

How reliable is this method?

Looking forward

Liked this article? Please 👏🏻 👏🏻 👏🏻 to show your love and encouragement to write more. 😍

--

--

The (retired) Pub(lication) for Android & Tech, focused on Development

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rahul Chowdhury

I send a newsletter every Friday to help you become 1% better every single week at hulry.com/newsletter