Открыть активность после нажатия в уведомлении в AlarmManager и трансляции Kotlin - PullRequest
1 голос
/ 11 февраля 2020

Я устанавливаю в своем приложении уведомление каждые 7 часов следующим образом:

  alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent(this, AlarmBroadcastReceiver::class.java)
        pendingIntent = PendingIntent.getBroadcast(this, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT)

        // Setting the specific time for the alarm manager to trigger the intent, in this example, the alarm is set to go off at 23:30, update the time according to your need
        val calendar = Calendar.getInstance()

        val next=  calendar.get(Calendar.HOUR_OF_DAY) + 7

        calendar.timeInMillis = System.currentTimeMillis()
        calendar.set(Calendar.HOUR_OF_DAY, next)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND,  0)

        // Starts the alarm manager
        alarmManager.setRepeating(
                AlarmManager.RTC_WAKEUP,
                calendar.timeInMillis,
                AlarmManager.INTERVAL_DAY,
                pendingIntent
        )

с этим классом AlarmBroadcastReceiver:

class AlarmBroadcastReceiver : BroadcastReceiver() {

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            // Create the NotificationChannel
            val name = "Alarme"
            val descriptionText = "Detalhes do Alarme"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val mChannel = NotificationChannel("AlarmId", name, importance)
            mChannel.description = descriptionText
            val notificationManager = context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(mChannel)
        }

        // Create the notification to be shown
        val mBuilder = NotificationCompat.Builder(context!!, "AlarmId")
                .setSmallIcon(R.mipmap.ic_food)
                .setContentTitle("Synchronize Fitbit")
                .setContentText("Synchronize Fitbit data and log-in SugarFree for don't lose daily data")
                .setAutoCancel(true)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)

        // Get the Notification manager service
        val am = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        // Generate an Id for each notification
        val id = System.currentTimeMillis() / 1000

        // Show a notification
        am.notify(id.toInt(), mBuilder.build())

Уведомления работают хорошо, я вхожу в приложение , установить будильник и через 7 часов прибыть уведомление и тд. Я sh сообщу, что когда я получу уведомление, я могу нажать на него и открыть приложение (возможно, в моем текущем домашнем активном режиме), поэтому этот будильник автоматически установится через 7 часов. Я понял, что должен изменить pendingIntent своим домашним намерением ... но у меня есть

val intent = Intent(this, AlarmBroadcastReceiver::class.java)

, которому нужно вызвать класс приемника тревог.

Кто-нибудь может мне помочь?

Ответы [ 2 ]

1 голос
/ 11 февраля 2020

Вам нужно создать и установить ожидающее намерение -

// Create an Intent for the activity you want to start
val resultIntent = Intent(this, YourMainActivity::class.java)
// Create the TaskStackBuilder
val resultPendingIntent: PendingIntent? = TaskStackBuilder.create(this).run {
    // Add the intent, which inflates the back stack
    addNextIntentWithParentStack(resultIntent)
    // Get the PendingIntent containing the entire back stack
    getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
} 

, а затем установить его -

val builder = NotificationCompat.Builder(this, CHANNEL_ID).apply {
    setContentIntent(resultPendingIntent)
    ...
}
with(NotificationManagerCompat.from(this)) {
    notify(NOTIFICATION_ID, builder.build())
}

Надеюсь, это сработает для вас.

1 голос
/ 11 февраля 2020

Все, что вам нужно, это добавить .setContentIntent в ваш построитель уведомлений.

// Create the notification to be shown
        val mBuilder = NotificationCompat.Builder(context!!, "AlarmId")
                .setSmallIcon(R.mipmap.ic_food)
                .setContentTitle("Synchronize Fitbit")
                .setContentText("Synchronize Fitbit data and log-in SugarFree for don't lose daily data")
                .setAutoCancel(true)
                .setContentIntent(PendingIntent.getActivity(
                    context, // Context from onReceive method.
                    0,
                    Intent(context, HomeActivity::class.java), // Activity you want to launch onClick.
                    0
                  )
                )
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .build()

Вы можете узнать больше здесь документы имеют больше информации о том, как обрабатывать такие задачи, как одновременно открывается только одно действие.

...