android - 使 AlarmManager 触发服务更新数据库
问题描述
因此,我正在尝试运行一项服务,该服务在每个午夜(大约)将某些房间数据发送到服务器并将其从本地数据库中删除。阅读 android 文档我得出的结论是,目前最好的方法是设置一个在午夜触发的警报并启动一个执行同步的服务)。虽然我不完全确定我应该使用哪种类型的服务,但我的文件如下所示:
MainActivity.kt
alarmMgr = applicationContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager?
alarmIntent = Intent(this, SendTakesReceiver::class.java).let { intent ->
PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
// Set the alarm to send takes at approximately 00:00 a.m.
val calendar: Calendar = Calendar.getInstance().apply {
timeInMillis = System.currentTimeMillis()
set(Calendar.HOUR_OF_DAY, 0)
}
// With setInexactRepeating(), you have to use one of the AlarmManager interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
alarmMgr?.setInexactRepeating(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
AlarmManager.INTERVAL_DAY,
alarmIntent
)
SendtakesReceiver.kt
class SendTakesReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
//these following logs are always shown
Log.d("TAKES INTENT", intent.toString())
if (intent != null) {
context?.run {
Log.d("TAKES SERVICE", intent.toString())
startService(intent)
}
}
}
}
SendTakesService.kt
class SendTakesService : Service() {
val sp: SharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE)
private var prescriptionTakeDao =
AppDatabase.getDatabase(applicationContext).prescriptionTakeDao()
override fun onCreate() {
super.onCreate()
Log.d("TakesService", "onCreate()")
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
}
最后在我的清单文件中(在应用程序标签内):
<receiver
android:name=".src.ui.prescriptions.SendTakesReceiver"
android:enabled="true" />
<service
android:name="com.glik.glik.src.services.SendTakesService"
android:enabled="true"
android:process=":SendTakes">
</service>
但问题是我尝试使用的所有服务类(Service、IntentService、JobIntentService)都没有调用它们的主要方法。例如,这里onCreate()
永远不会显示日志。我已经看到无数关于服务未启动的类似问题,但我似乎无法确定我在这里犯的导致服务无法启动的确切错误。如果有人可以帮助我找到它,或者推荐一种更优雅的方法来进行数据库同步,我将非常感激。提前致谢。
解决方案
根据您使用的手机的 OEM,您将面临这种方法的各种挑战。见https://dontkillmyapp.com/
您应该使用 WorkManager以减少电池使用量并避免不得不手动处理许多极端情况:https ://developer.android.com/topic/libraries/architecture/workmanager/basics
推荐阅读
- java - 使用 EventHandler 更改图形
- python-3.x - Python 3 原始字节字符串
- c# - Razor 页面等待 Blazor 组件完成渲染的规范方式是什么?
- java - 如何使用 Java NetBeans 改组图像
- opencart - opencart 1.5.6.4 版本小更新
- javascript - 如何在 Vue js 中将 FileReader 用于两个或多个输入字段?
- python - 如何创建一个包含单引号和双引号 python 的字符串?
- scala - Spark:mapPartitions 对象不可序列化
- html - 调整表格中单元格的大小
- sql - 具有唯一行集的左外连接