0

У меня есть список: listDateTime состоящий из LocalDataTime. Она содержит в себе следующее: [2019-10-02T13:50, 2019-10-01T14:00, 2019-10-01T08:23].

Как реализовать правильную работу уведомлений по дате и времени?

fun onRealTask() {
    for (i in 0 until listDateTime.count()){
        Notificationss().addNotificat("Notifications-$i", listDateTime[i], i)
    }
}

TiviTypeConverters.fromStringLDTtoStringDT переводит LocalDataTime в String


class Notificationss: BasicNotification {

companion object {
    const val WHERE_ACTION = "android.intent.action.MAIN_NOTIFICATION"
}

override fun addNotificat(notificationsMessage: String, notificationsDate: LocalDateTime, i: Int) {

    val date_now = LocalDateTime.now(ZoneOffset.UTC).atZone(ZoneOffset.UTC).toEpochSecond()
    val date_inspection = notificationsDate.atZone(ZoneOffset.UTC).toEpochSecond()

    val intent = Intent(context, NotificationReceiver::class.java)

    intent.action = WHERE_ACTION
    intent.putExtra("Message", notificationsMessage)

    intent.putExtra("Date", TiviTypeConverters.fromStringLDTtoStringDT(notificationsDate.toString()))
    intent.putExtra("id", i)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

    val pendingIntent =
                PendingIntent.getBroadcast(
                context, 0,
                intent, PendingIntent.FLAG_CANCEL_CURRENT
        )

    val calendar = Calendar.getInstance()
    calendar.timeInMillis = System.currentTimeMillis()
    calendar.add(Calendar.SECOND, (date_inspection - date_now).toInt())
    val time = calendar.timeInMillis

    if (date_inspection > date_now) {
        val alarmManager = context.getSystemService(ALARM_SERVICE) as AlarmManager

        if (android.os.Build.VERSION.SDK_INT >= 19){
             Log.d("my", "------- Через ${(date_inspection - date_now)} сек -------")
             alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent)   }
       else{
             alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent)
       }


   } else {
       Log.d("my", "------------Дата прошла!!!-------------")
        }
}}

Manifest

        ...
    <receiver
        android:name=".app.service.NotificationReceiver"
        android:enabled="true"
        android:exported="false">
        <intent-filter>
            <action android:name="android.intent.action.MAIN_NOTIFICATION" />
        </intent-filter>
    </receiver>

NotificationReceiver

class NotificationReceiver: BroadcastReceiver() {


override fun onReceive(context: Context, intent: Intent) {

    val notificationsMessage = intent.getStringExtra("Message")
    val notificationsDate =  intent.getStringExtra("Date")
    val id = intent.getIntExtra("id", 123)

    val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)

    val notification =  NotificationCompat.Builder(context, "125")
            .setSmallIcon(R.mipmap.ic_app)
            .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_app))
            .setContentTitle("$notificationsMessage-----${ LocalDateTime.now()}")
            .setContentText("Ожидается проверка $notificationsDate")
            .setContentIntent(pendingIntent)
            .setColor(Color.DKGRAY)
            .setAutoCancel(true)

    val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    nm.notify(id, notification.build())

}

}

4
  • Мне кажется вы свалили в одну кучу push notifications и local notifications. Ваш случай -- это второй тип. Соответственно сервис вам не нужен, он для первых. 2 окт 2019 в 19:32
  • @EugeneKrivenja local notifications будет работать при закрытом приложении без сервиса?
    – isa
    3 окт 2019 в 5:28
  • При закрытом приложении ничего не работает. Чтобы заработало, нужно чтобы приложение кто-то "пнул" извне. Будет это push notification или AlarmManager или еще чего, решать вам. 3 окт 2019 в 10:23
  • К тому же ваш NotificationService вообще и близко не сервис, а BroadcastReceiver. Это разные вещи. 3 окт 2019 в 10:24

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.