Last active
February 23, 2021 15:26
-
-
Save rotman/9e59b6e2cfea431628dfceaad6c1d2f5 to your computer and use it in GitHub Desktop.
Create your foreground task
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ReposForegroundService : ForegroundTaskService() { | |
override fun getNotification(): Notification { | |
// create channel | |
val channelId = resources.getString(R.string.my_channel) | |
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { | |
val notificationChannel = NotificationChannel(channelId, channelId, NotificationManager.IMPORTANCE_DEFAULT) | |
notificationChannel.setSound(null, null) | |
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager | |
notificationManager.createNotificationChannel(notificationChannel) | |
} | |
return NotificationCompat.Builder(this, channelId) | |
.setContentTitle(resources.getString(R.string.my_title)) | |
.setContentText(resources.getString(R.string.my_body)) | |
.setSmallIcon(R.drawable.ic_launcher_foreground) | |
.build() | |
} | |
// Called from a background thread | |
override fun doWork(): Result { | |
return try { | |
val repos = GitHubRepo(getNetworkService()).getRepos().execute() | |
Result.Success | |
} catch (e: Exception) { | |
if (foregroundTaskInfo.retryCount >= MAX_RETRIES) { | |
Result.Failed | |
} else { | |
Result.Retry | |
} | |
} | |
} | |
override fun onStop(stoppedCause: StoppedCause): Result { | |
return when (stoppedCause) { | |
StoppedCause.Timeout -> onTimeout() // called when timeout was reached according to ForegroundTaskInfo.timeoutMillis | |
StoppedCause.ConnectionNotAllowed -> Result.Retry // called when connection type was changed while work is being executed | |
StoppedCause.TerminatedBySystem -> Result.Failed // called when the system decided to stop the task while work is being executed | |
} | |
} | |
private fun onTimeout(): Result { | |
return if (foregroundTaskInfo.retryCount >= MAX_RETRIES) { | |
Result.Failed | |
} else { | |
Result.Retry | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment