BroadcastReceiver не получает намерение, если оно зарегистрировано в коде, но если в манифесте, оно получаетAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 BroadcastReceiver не получает намерение, если оно зарегистрировано в коде, но если в манифесте, оно получает

Сообщение Anonymous »

Я столкнулся с проблемой: мой приемник просто не работает, если я регистрирую его в своей активности, но если я регистрирую его в манифесте, он работает хорошо.
Этот приемник должен обрабатывать намерение, которое отправляется после кнопки щелкнул уведомление.
Для тестирования я создал новый простой проект.
В манифесте я добавил разрешение на уведомление: В Activity мы просто сразу создаем уведомление, вот полный код активности:

Код: Выделить всё

import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat

class MainActivity : ComponentActivity() {

private val receiver = CancelNotificationReceiver()

@SuppressLint("MissingPermission")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

val filter = IntentFilter(CancelNotificationReceiver.NOTIFICATION_CANCEL_ACTION)
ContextCompat.registerReceiver(
this,
receiver,
filter,
ContextCompat.RECEIVER_EXPORTED
)

val channelIdStr = "channel"

val closeIntent = Intent(this, CancelNotificationReceiver::class.java).apply {
action = CancelNotificationReceiver.NOTIFICATION_CANCEL_ACTION
}
val closePendingIntent: PendingIntent =
PendingIntent.getBroadcast(
this, 0, closeIntent,
PendingIntent.FLAG_MUTABLE
)

val builder = NotificationCompat.Builder(this, channelIdStr)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Title")
.setContentText("Text")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.addAction(
0, "Close",
closePendingIntent
)

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val importance = NotificationManager.IMPORTANCE_LOW
val channel = NotificationChannel(channelIdStr, "channelName", importance).apply {
description = "channelDescription"
}
val notificationManager: NotificationManager =
this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}

NotificationManagerCompat.from(this).apply {
notify(1, builder.build())
}
}
}
А вот приемник:

Код: Выделить всё

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast

class CancelNotificationReceiver : BroadcastReceiver() {

companion object {
const val NOTIFICATION_CANCEL_ACTION = "NOTIFICATION_CANCEL_ACTION"
}

override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
NOTIFICATION_CANCEL_ACTION -> {
Toast.makeText(context, "canceled", Toast.LENGTH_SHORT).show()
}
}
}
}
Поэтому, если пользователь нажимает кнопку в уведомлении, должен отображаться тост с текстом «отменено», но это не так.
Но когда я регистрирую своего получателя в манифесте таким образом, он начинает работать: Но я хочу регистрировать получатели не в своем коде, а не в манифесте.
Я читаю https://developer. android.com/develop/ui/views/notifications/build-notification и https://developer.android.com/develop/b ... broadcasts документацию, но не понимаю, что произошло не так.

Подробнее здесь: https://stackoverflow.com/questions/784 ... -in-manife
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»