在我的前台服务中,我需要连接到我的后端以每 3 分钟下载一次最新数据并在通知中显示数据。经过几分钟的谷歌搜索,似乎使用“ScheduledThreadPoolExecutor”是最好的。但我仍然不清楚池大小应该放什么。
在决定池大小时应该考虑什么?基本上我的前台服务将做的是:
- 每 180 秒连接一次 API
- 使用 Room 将数据保存在 db 中
- 显示通知下面是我的一些代码:
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
}
}