(оно работает нормально, когда приложение находится на переднем плане или в фоновом режиме).
В моем приложении есть требование выполнять службу переднего плана в определенном диапазоне времени дня. Для этого я использую AlarmManager, чтобы запланировать запуск и остановку службы через нужные интервалы времени.
и какие существуют способы, кроме AlarmManager, для планирования службы приоритетного плана.
Класс TimeBasedScheduler:
Код: Выделить всё
class TimeBasedScheduler : BroadcastReceiver() {
private val TAG = "TimeBasedScheduler"
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
Log.d(TAG, "Received action: $action")
if (action != null) {
when (action) {
"START_SERVICE" -> {
Log.d(TAG, "Initializing socket for START_SERVICE")
initializeSocket(context)
// Now execution is started and resumed
LocalPrefrenceUtils.insertDataInBoolean(context, AppConstants.BACKGROUND_WORK_ALLOWED_KEY_FOR_LOCAL_PREFERENCE, true)
LocalPrefrenceUtils.insertDataInBoolean(context, AppConstants.BACKGROUND_WORK_TEMPORARILY_PAUSED_KEY_FOR_LOCAL_PREFERENCE, false
)
}
"STOP_SERVICE" -> {
Log.d(TAG, "Stopping service for STOP_SERVICE")
LocalPrefrenceUtils.insertDataInBoolean(
context,
AppConstants.BACKGROUND_WORK_TEMPORARILY_PAUSED_KEY_FOR_LOCAL_PREFERENCE,
true
)
val stopIntent = Intent(context, SocketManagerService::class.java)
context.stopService(stopIntent)
}
}
}
}
private fun initializeSocket(context: Context?) {
Log.d(TAG, "Initializing socket")
val intent = Intent(context, SocketManagerService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Log.d(TAG, "Starting foreground service")
context?.startForegroundService(intent)
} else {
Log.d(TAG, "Starting service")
context?.startService(intent)
}
}
}
Код: Выделить всё
private fun setupForegroundServiceAlarms() {
val TAG = "TaskBasedScheduler"
// Get the start and end times from preferences
val startTime = LocalPrefrenceUtils.getStartTime(this)
val endTime = LocalPrefrenceUtils.getEndTime(this)
Log.d(TAG, "Start Time: $startTime")
Log.d(TAG, "End Time: $endTime")
// Calculate start and end times based on step sizes and special cases for value 48
val startHour = 7 // Starting hour (7:00 am)
val stepSizeMinutes = 30 // Step size in minutes
val startHourForAlarms = startHour + (stepSizeMinutes * startTime) / 60
val endHourForAlarms = if (endTime == 48) startHour + (stepSizeMinutes * endTime) / 60 - 1 else startHour + (stepSizeMinutes * endTime) / 60
val startMinute = (stepSizeMinutes * startTime) % 60
val endMinute = if (endTime == 48) ((stepSizeMinutes * endTime) % 60) - 1 else ((stepSizeMinutes * endTime) % 60)
// Set the Calendar instances for start and end times
val startCalendar = Calendar.getInstance().apply {
timeInMillis = System.currentTimeMillis()
set(Calendar.HOUR_OF_DAY, startHourForAlarms)
set(Calendar.MINUTE, startMinute)
set(Calendar.SECOND, 0)
}
val endCalendar = Calendar.getInstance().apply {
timeInMillis = System.currentTimeMillis()
set(Calendar.HOUR_OF_DAY, endHourForAlarms)
set(Calendar.MINUTE, endMinute)
set(Calendar.SECOND, 0)
}
Log.d(TAG, "Start Calendar Time: ${startCalendar.time}")
Log.d(TAG, "End Calendar Time: ${endCalendar.time}")
// Cancel previously set alarms
alarmManager.cancel(startPendingIntent)
alarmManager.cancel(endPendingIntent)
Log.d(TAG, "Canceled previous alarms")
// Create intents for starting and stopping the service
val startIntent = Intent(this, TimeBasedScheduler::class.java).apply {
action = "START_SERVICE"
}
val endIntent = Intent(this, TimeBasedScheduler::class.java).apply {
action = "STOP_SERVICE"
}
// Create pending intents for start and end actions
startPendingIntent = PendingIntent.getBroadcast(this, 0, startIntent, PendingIntent.FLAG_IMMUTABLE)
endPendingIntent = PendingIntent.getBroadcast(this, 1, endIntent, PendingIntent.FLAG_IMMUTABLE)
Log.d(TAG, "Created pending intents")
// Set alarms using AlarmManager for daily repetition
alarmManager.setInexactRepeating(
AlarmManager.RTC_WAKEUP,
startCalendar.timeInMillis,
AlarmManager.INTERVAL_DAY,
startPendingIntent
)
alarmManager.setInexactRepeating(
AlarmManager.RTC_WAKEUP,
endCalendar.timeInMillis,
AlarmManager.INTERVAL_DAY,
endPendingIntent
)
Log.d(TAG, "Alarms set for start: ${startCalendar.time}, end: ${endCalendar.time}")
}
Код: Выделить всё

Получатель, когда приложение находится на переднем или заднем плане:

Я проверил журналы с помощью Logcat, и он не показывает никаких сообщений об ошибках, связанных с сигналами тревоги или тем, что служба переднего плана не запускается.
Мне нужны инструкции, почему сигналы тревоги не запускают службу переднего плана, как ожидалось. Буду признателен за любые идеи, предложения и потенциальные решения по решению этой проблемы.
Спасибо за помощь.
Подробнее здесь: https://stackoverflow.com/questions/775 ... round-serv