0

在我的前台服务中,我需要连接到我的后端以每 3 分钟下载一次最新数据并在通知中显示数据。经过几分钟的谷歌搜索,似乎使用“ScheduledThreadPoolExecutor”是最好的。但我仍然不清楚池大小应该放什么。

在决定池大小时应该考虑什么?基本上我的前台服务将做的是:

  1. 每 180 秒连接一次 API
  2. 使用 Room 将数据保存在 db 中
  3. 显示通知下面是我的一些代码:
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
        }
    }
4

1 回答 1

1

哈伊敏!

您的池大小只是在任何给定时间池中存在的线程数量。考虑到下载/等待数据可以存在于一个线程上,并且您将其发送到另一个线程以显示为通知,我认为 2 个线程可以为您完成这项工作。如果您注意到性能问题,可以考虑尝试 1,因为您对事件有特定的顺序,并且它们不会同时发生,除非 API 需要 180 秒来传递通知数据。

我知道在应用程序中,您会使用专用的 UI 线程将任何数据从后台线程移动到屏幕上,但我不确定这是否是通知的选项。

希望这有帮助!

于 2021-10-06T16:53:05.147 回答