Имею отложенные Уведомления на телефоне в своем приложение (12:00, 17:00, 21:00)
Запускаю уведомление по схеме AlarmManager -> BroadcastReciver -> NotificationService -> create and start Notivication.
Проверяю на 3 версиях android: [4.3], [7.1], [9.0]
[4.3] + [7.1] : исправно присылает оповещения в без укарезноно даже при проверки смены времени в настройках при закрытом приложении
[9.0] : дает сбои в работе (он присылает а то не присылает уведомления) при изменение времени или даты вообще ничего не происходит
Проблема не понятна почему все работает с перебоями
NotificationHelper
class NotificationHelper(var ctx: Context, var id: Int) {
private lateinit var mNotificationManager: NotificationManager
private lateinit var mBuilder: NotificationCompat.Builder
private val NOTIFICATION_CHANNEL_NAME = "Diets"
fun creatNotivication(title: String, message: String) {
val intentResult = Intent(ctx, MainActivity::class.java )
intentResult.flags = Intent.FLAG_ACTIVITY_NEW_TASK
val peddingIntent: PendingIntent = PendingIntent.getActivities(ctx,0, arrayOf(intentResult),PendingIntent.FLAG_UPDATE_CURRENT)
mBuilder = NotificationCompat.Builder(ctx, "$id")
mBuilder.setSmallIcon(com.papaya.diets.R.drawable.notification_icon)
mBuilder.setContentTitle(title)
.setContentText(message)
.setAutoCancel(false)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setContentIntent(peddingIntent)
mNotificationManager = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
var importance = NotificationManager.IMPORTANCE_HIGH
var notificationChannel = NotificationChannel("$id" ,NOTIFICATION_CHANNEL_NAME, importance)
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.RED
notificationChannel.enableVibration(true)
notificationChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
mBuilder.setChannelId("$id")
mNotificationManager.createNotificationChannel(notificationChannel)
}
mNotificationManager.notify(id, mBuilder.build())
}
}
Alarm in MainActivity
fun startNotification(ctx: Context, id: Int, hours: Int, interval: Long, countCup: Int) {
var notificationIntent = Intent(ctx, NotificationReceiver::class.java)
notificationIntent.putExtra("countCups", countCup)
notificationIntent.putExtra("notifId", id)
notificationIntent.putExtra("hours", hours)
notificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND)
val pendingIntent = PendingIntent.getBroadcast(ctx, id, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT)
// val calundar2 = Helper().createCurrentCalendarTime()
val calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY, hours)
calendar.set(Calendar.MINUTE, 0)
calendar.set(Calendar.SECOND, 0)
// if (calendar.compareTo(calundar2) < 0) {
// calendar.add(Calendar.DATE, 1)
// }
Log.v("Notification", "alarm ${calendar.time} notification start")
var alarmManager = ctx.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.cancel(pendingIntent)
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
AlarmManager.INTERVAL_DAY,
pendingIntent
)
}
NotivicationReciver
class NotificationReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val id = intent.extras!!.getInt("notifId")
val countCups = intent.extras!!.getInt("countCups")
val hours = intent.extras!!.getInt("hours")
val intent1 = Intent(context, NotificationService::class.java)
intent1.putExtra("notifId", id)
intent1.putExtra("countCups", countCups)
intent1.putExtra("hours", hours)
context.startService(intent1)
println("BroadcastReceiver START TEST")
}
}
NotificationService
class NotificationService : IntentService("Notify") {
override fun onHandleIntent(intent: Intent?) {
println("SERVICE START TEST")
val id = intent!!.extras!!.getInt("notifId")
val count = intent.extras!!.getInt("countCups")
val hours = intent.extras!!.getInt("hours")
val water = RealmHelper().changeWaterCup()
var countCups = 0
water!!.forEach {
if (it) {
countCups = countCups.plus(1)
}
}
if (countCups < count) {
println("notificaion $id")
NotificationHelper(applicationContext, id).creatNotivication(
"Пора выпить воды",
"Не забудьте отметить выпитый стаканчик в приложении"
)
}
}
}
Manifest
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-feature android:name="android.hardware.camera"/>
<receiver android:name=".Service.NotificationReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
<service
android:name=".Service.NotificationService"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="NOTIFICATION_SERVICE"/>
</intent-filter>
</service>