首页 > 解决方案 > Android:不允许后台执行:接收意图

问题描述

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

清单文件.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>

标签: javaandroidandroid-intentnotificationsnative

解决方案


首先

无法克服此错误

哪个错误?没有日志,没有信息什么不起作用...这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;

在低于 26 的 API 上假设它在那里


推荐阅读