首页 > 解决方案 > 使 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()永远不会显示日志。我已经看到无数关于服务未启动的类似问题,但我似乎无法确定我在这里犯的导致服务无法启动的确切错误。如果有人可以帮助我找到它,或者推荐一种更优雅的方法来进行数据库同步,我将非常感激。提前致谢。

标签: androidkotlinserviceretrofit2alarmmanager

解决方案


根据您使用的手机的 OEM,您将面临这种方法的各种挑战。见https://dontkillmyapp.com/

您应该使用 WorkManager以减少电池使用量并避免不得不手动处理许多极端情况:https ://developer.android.com/topic/libraries/architecture/workmanager/basics


推荐阅读