Как открыть приложение при нажатии на уведомление в android? - PullRequest
1 голос
/ 27 мая 2020

Я уже сделал уведомление без намерения MainActivity, и оно работает нормально, но когда я добавляю это намерение в свой MainActivity, уведомление больше не отображается. Что-то не так с моим кодом, или мне нужно изменить манифест или добавить код в мою MainActivity?

Вот мой код. Я установил для него две функции - setDailyReminder и showAlarmNotification.

fun setDailyReminder(context: Context, type: String, message: String) {
    val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
    val intent = Intent(context, MainActivity::class.java)
    intent.putExtra(EXTRA_MESSAGE, message)
    intent.putExtra(EXTRA_TYPE, type)
    val timeArray =
        TIME_DAILY.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
    val calendar = Calendar.getInstance()
    calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeArray[0]))
    calendar.set(Calendar.MINUTE, Integer.parseInt(timeArray[1]))
    calendar.set(Calendar.SECOND, 0)
    val pendingIntent = PendingIntent.getBroadcast(context,
        ID_DAILY, intent, 0)
    alarmManager.setInexactRepeating(
        AlarmManager.RTC_WAKEUP,
        calendar.timeInMillis,
        AlarmManager.INTERVAL_DAY,
        pendingIntent
    )
    Toast.makeText(context, "Daily reminder set up", Toast.LENGTH_SHORT).show()
}

private fun showAlarmNotification(
    context: Context,
    title: String,
    message: String?,
    notifId: Int
) {

    val CHANNEL_ID = "Github App"
    val CHANNEL_NAME = "Let's find favourite user on Github"

    val notificationManagerCompat =
        context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    val alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
    val builder = NotificationCompat.Builder(context, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_play_circle_filled_white_24dp)
        .setContentTitle(title)
        .setContentText(message)
        .setSound(alarmSound)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channel = NotificationChannel(
            CHANNEL_ID,
            CHANNEL_NAME,
            NotificationManager.IMPORTANCE_DEFAULT
        )
        builder.setChannelId(CHANNEL_ID)
        notificationManagerCompat.createNotificationChannel(channel)
    }
    val notification = builder.build()
    notification.flags = notification.flags or Notification.FLAG_AUTO_CANCEL
    notificationManagerCompat.notify(notifId, notification)
}

1 Ответ

1 голос
/ 27 мая 2020
 fun showNotification(context: Context,title: String, message:String, notifId: Int){

       createNotificationChannel(context)

       val intent = Intent(context, MainActivity::class.java)
       intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
       val pendingIntent = PendingIntent.getActivity(this, 0, 
       intent,PendingIntent.FLAG_ONE_SHOT)

        var  builder = NotificationCompat.Builder(context, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_play_circle_filled_white_24dp)
            .setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(true)
            .setColor(resources.getColor(R.color.colorAccent))
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent)

        val notificationManagerCompat = NotificationManagerCompat.from(this)
        notificationManagerCompat.notify(notifId, builder.build())
    }

    private fun createNotificationChannel(context: Context) {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "Test"
            val descriptionText = "FCM"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
                description = descriptionText
            }
            // Register the channel with the system
            val notificationManager: NotificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...