In my foreground service, I need to connect to my backend to download the latest data once every 3 minutes and display the data on a notification. After a few minutes of googling, it seems using 'ScheduledThreadPoolExecutor' would be the best. But I'm still not clear on what to put for the pool size.
What's the consideration that I should take when deciding the pool size? Basically what my foreground service will be doing is:
- Connect to an API every 180 seconds
- Save the data in db using Room
- Display notification Below is some of my code:
class BusinessService: Service() {
private var job: Job? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val notificationIntent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0)
val exec = ScheduledThreadPoolExecutor(3)
val delay: Long = 180
exec.scheduleWithFixedDelay(object : Runnable {
override fun run() {
CoroutineScope(Dispatchers.IO).launch {
val params = HashMap<String, String>()
params["email"] = "test@gmail.com"
val sellerLoginResult = EarthlingsApi.retrofitService.sellerLogin(params)
when (sellerLoginResult) {
is NetworkResponse.Success -> {
Timber.d(sellerLoginResult.body.msg)
}
}
val channelId =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel("my_service", "My Background Service")
} else {
""
}
val notification = NotificationCompat.Builder(myContext, channelId)
.setContentTitle(getString(R.string.Business_Notification_Header,name))
.setContentText(getString(R.string.Business_Notification_Content,"7"))
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentIntent(pendingIntent)
.build()
startForeground(111, notification)
}
}
}, 0, delay, TimeUnit.SECONDS)
return START_STICKY
}
}