Android:不允许后台执行:接收 Intent

Android: Background execution not allowed: receiving Intent

我正在尝试使用警报管理器发送通知,代码在较低的 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>

首先

not able to go past this error

哪个错误?没有日志,没有信息什么不起作用...此 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 假设它在那里

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);