Android AlarmManager не работает, когда приложение находится в фоновом режиме - PullRequest
0 голосов
/ 25 октября 2019

У меня проблема с AlarmManager. Когда мое приложение на переднем плане, все хорошо, но когда не работает фоновая сигнализация. Когда я возвращаюсь к приложению, оно запускает будильник. Мой код: https://pastebin.com/1bKN6PKt Манифест:

MyApp.kt

registerReceiver(
    AlarmNotificationConfirmBroadcastReceiver(),
    IntentFilter("pl.app.alert_confirm")
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    val name = getString(R.string.channel_name)
    val descriptionText = getString(R.string.channel_description)
    val importance = NotificationManager.IMPORTANCE_DEFAULT
    val channel =
NotificationChannel(
    AlarmNotificationBroadcastReceiver.ALARM_NOTIFICATION_CHANNEL_NAME,
    name,
    importance
).apply {
    description = descriptionText
}
    val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    notificationManager.createNotificationChannel(channel)
}

MyFragment.kt:

val intent = Intent(context, AlarmNotificationBroadcastReceiver::class.java)
intent.putExtra("action", "alarm")
val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val alarmTimeDelay = System.currentTimeMillis() + (5 * 60000)

val alarmService = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    alarmService.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmTimeDelay, pendingIntent)
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    alarmService.setExact(AlarmManager.RTC_WAKEUP, alarmTimeDelay, pendingIntent)
} else {
    alarmService.set(AlarmManager.RTC_WAKEUP, alarmTimeDelay, pendingIntent)
}

AlarmNotificationBroadcastReceiver.kt:

ALARM_NOTIFICATION_CHANNEL_NAME = "pl.app.channel"

val alarmIntent = Intent("pl.app.alert_confirm")
val pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT)

val builder = NotificationCompat.Builder(context, ALARM_NOTIFICATION_CHANNEL_NAME)
    .setContentTitle(context.getString(R.string.confirm_title))
    .setContentText(context.getString(R.string.confirm_message))
    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    .setOnlyAlertOnce(true)
    .setContentIntent(pendingIntent)
    .setAutoCancel(true)
with(NotificationManagerCompat.from(context)) {
    notify(3, builder.build())
}

AlarmNotificationConfirmBroadcastReceiver.kt

val sharedPreferences  = context.getSharedPreferences("app_file", 0)
sharedPreferences.edit().putString("active", "1").apply()

Спасибо за помощь

...