java - 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>
解决方案
首先
无法克服此错误
哪个错误?没有日志,没有信息什么不起作用...这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 上假设它在那里
推荐阅读
- python - 熊猫系列地图
- python-3.x - 根据其他 csv 的匹配值向 csv 文件添加两列
- python - 在 Python 中枚举相机
- node.js - NodeJS 类结构中的 MongoDB
- c# - 使用身份验证 ASP.NET MVC 中的用户
- swift - Swift 中带有通配符(或小丑)的字谜
- android - 如何将我的 Unity android 构建包集成到另一个 Android 应用程序?
- firefox - SVG 的边缘在 Firefox 中被切断
- php - 调用未定义的方法 Illuminate\Support\Facades\Gate::define()
- git - 如何让每个人都在本地删除已从原点删除的 git 分支