Android: выполнение в фоновом режиме запрещено: получение намерения - PullRequest
0 голосов
/ 17 июня 2020

Я пытаюсь отправить уведомление с помощью диспетчера аварийных сигналов, код работает нормально с более ранними версиями SDK, например 26 ниже. Неявный фоновый бан android не позволяет уведомлению транслироваться.

найдите код ниже для BroadcastReceiver:

public class AlarmReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {

System.out.println("AlarmReceiver-Worked");

MainActivity.initNotificationChannels(context);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, "default")
       .setDefaults(Notification.DEFAULT_ALL)
       .setSmallIcon(R.mipmap.ic_launcher)                                      
       .setContentTitle(intent.getStringExtra("title"))
       .setContentText(intent.getStringExtra("text"))
       .setContentIntent(pendingIntent)
       .setPriority(Notification.PRIORITY_MAX);

NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
  }
 }

Manifext. xml

<receiver android:name="com.x.Controllers.Notification.AlarmReceiver"
          android:enabled="true"
          android:exported="true">
  <intent-filter>
     <action android:name="android.media.action.DISPLAY_NOTIFICATION" />
     <category android:name="android.intent.category.DEFAULT" />
  </intent-filter>
</receiver>

Ответы [ 2 ]

0 голосов
/ 19 июня 2020
Intent notificationIntent = new Intent(context, AlarmReceiver.class);                           
notificationIntent.setAction("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.putExtra("title", notificationData.getString("title"));
notificationIntent.putExtra("text", notificationData.getString("text"));

PendingIntent broadcast = PendingIntent.getBroadcast(this.context, i, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), broadcast);
0 голосов
/ 17 июня 2020

прежде всего

не удалось go пройти эту ошибку

какая ошибка? нет журнала, нет информации что не работает ... для каких действий этот BroadcastReceiver зарегистрирован? это для BOOT_COMPLETED или чего-то еще?

кроме этого

private static boolean notificationChannelsInitialized = false;

if (notificationChannelsInitialized) {
    return;
}

он всегда будет return здесь, вы устанавливаете этот флаг на true позже в этом методе, Этого никогда не случится.

также не используйте флаг static, просто убедитесь, что Channel уже существует

NotificationChannel channel = manager.getNotificationChannel("default");
notificationChannelsInitialized = Build.VERSION.SDK_INT < 26 || channel != null;

в API ниже 26 просто предположите, что он есть

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...