【发布时间】:2018-07-25 12:52:41
【问题描述】:
我想要实现的是创建一个服务(?),它在安装应用程序后启动/注册,并将监控项存储在数组中。这些商品是有到期日的产品,所以如果今天是到期日,我想显示关于它的通知,无论应用程序当前是否正在运行。
我已经在互联网和 Android 开发者网站上搜索了答案,以下是我了解到的:
- 我需要创建一个服务,它在 onStartCommand 返回“START_STICKY”并在我的 android Manifest.xml 文件中指定 Activity 处于 SingleTop 启动模式。
- 我需要将此 Service 与我的 Activity 绑定,以便以一种或另一种方式传递数据。
我不知道该怎么做:
- 在哪里启动服务,所以只有 1 个实例?
- 如何检查存储在数组中(在服务或活动中)的到期日期,例如每天一次?
- 包含产品的数组,它应该是静态的,以便可以从 Activity 和 Service 访问,还是我应该创建它的单独实例并通过 Binder 相应地传递数据?
一般来说,我知道基础知识以及它应该如何工作,但我缺乏如何实施它以便它有效的概念。
感谢所有回答! :)
// 编辑
目前我的自定义服务的一些代码:
class ExpiryMonitorService : Service() {
private val productsArray: ArrayList<ProductEntry> = ArrayList()
// Binder which will be given to clients
private val mBinder: IBinder = LocalBinder()
inner class LocalBinder : Binder() {
fun getService() : ExpiryMonitorService {
// Return this instance of ExpiryMonitorService so clients can call public methods
return this@ExpiryMonitorService
}
}
override fun onBind(intent: Intent?): IBinder {
return mBinder
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return START_STICKY // Restart this service if it gets killed by the system
}
}
【问题讨论】:
标签: android service background-process android-binder