【问题标题】:poolsize for ScheduledThreadPoolExecutor running in foregroundservice在前台服务中运行的 ScheduledThreadPoolExecutor 的 poolsize
【发布时间】:2021-11-26 20:42:33
【问题描述】:

在我的前台服务中,我需要连接到我的后端以每 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
        }
    }

【问题讨论】:

    标签: android kotlin android-threading


    【解决方案1】:

    嘿嘿!

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

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

    希望这有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-01
      • 2019-05-14
      • 1970-01-01
      • 2020-01-19
      • 2014-04-11
      相关资源
      最近更新 更多