Пытаюсь реализовать ежедневные оффлайн уведомления/напоминания (строго в определенное пользователем время). Пробовал через AlarmManager, но у него недостаток - если приложение принудительно закрыть или устройство перезагрузить, уведомление перестанет приходить. WorkManager вроде как не может отправлять уведомление в указанное время. У кого есть опыт в этой теме, расскажите как это реализовать. Желательно на Java. Заранее благодарен.
1 ответ
В Manifest
добавляем:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
// Чтобы "ловить" перезагрузку, выключение
<receiver android:name=".receiver.BootCompleteReceiver"
android:enabled="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
// Чтобы "ловить" смену времени
<receiver android:name=".receiver.TimeChangedReceiver">
<intent-filter>
<action android:name="android.intent.action.TIME_SET" />
</intent-filter>
</receiver>
// Наши уведомления
<receiver android:name=".receiver.NotificationReceiver" />
BootCompleteReceiver
:
class BootCompleteReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == Constants.BOOT_COMPLETED) {
AlarmsUtility.setAlarm(context)
}
}
}
TimeChangedReceiver
:
class TimeChangedReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == Constants.TIME_SET) {
AlarmsUtility.setAlarm(context)
}
}
}
NotificationReceiver
:
class NotificationReceiver : BroadcastReceiver() {
private lateinit var notificationManager: NotificationManagerCompat
override fun onReceive(context: Context, intent: Intent) {
notificationManager = NotificationManagerCompat.from(context)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel()
}
var text = "Уведомление"
val builder = getNotificationBuilder(context).setContentText(text)
notificationManager.notify(Constants.NOTIFICATION_ID, builder.build())
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel() {
val channel = NotificationChannel(
Constants.NOTIFICATION_CHANNEL_ID,
Constants.NOTIFICATION_CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT
)
notificationManager.createNotificationChannel(channel)
}
private fun getNotificationBuilder(context: Context) =
NotificationCompat.Builder(context, Constants.NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(null)
.setContentText(null)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setCategory(NotificationCompat.CATEGORY_EVENT)
}
AlarmsUtility
:
object AlarmsUtility {
fun setAlarm(context: Context) {
val hour = 12 // Час уведомления, можно брать с настроек
val minute = 0 // Минуты уведомления, можно брать с настроек
val calendar = Calendar.getInstance().apply {
timeInMillis = System.currentTimeMillis()
set(Calendar.HOUR_OF_DAY, hour)
set(Calendar.MINUTE, minute)
}
val broadcastIntent = Intent(context, NotificationReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(context, 0, broadcastIntent, 0)
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
AlarmManager.INTERVAL_DAY,
pendingIntent
)
}
fun cancelAlarm(context: Context) {
val broadcastIntent = Intent(context, NotificationReceiver::class.java)
val pendingIntent =
PendingIntent.getBroadcast(context, 0, broadcastIntent, PendingIntent.FLAG_NO_CREATE)
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.cancel(pendingIntent)
}
}
Я в манифесте поставил BootCompleteReceiver = false
, чтобы включать его самостоятельно из кода, и отключать когда уведомления выключены:
val bootCompleteReceiver = ComponentName(requireActivity(), BootCompleteReceiver::class.java)
if (...) {
requireActivity().packageManager.setComponentEnabledSetting(
bootCompleteReceiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP
)
AlarmsUtility.setAlarm(requireContext())
} else {
requireActivity().packageManager.setComponentEnabledSetting(
bootCompleteReceiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP
)
AlarmsUtility.cancelAlarm(requireContext())
}
Думаю тоже самое необходимо прописывать для TimeChangedReceiver
. Не уверен, более опытные подскажут.
Извиняюсь за качество написанного кода и изложения своих мыслей.
-
Благодарю. Также очень желательно из приложения попросить пользователя включить автостарт приложения и отключить "умный режим" который может убить ваше приложение 15 июл 2021 в 5:07