不允许后台执行.Android O pendingintent

Jas*_*son 10 android broadcastreceiver android-intent android-notifications android-8.0-oreo

我有一个服务,安排pendingintent开始我的通知.但是,因为Android OI出现此错误.我做了一些研究,偶然发现context.registerReceiver,但这似乎并没有解决问题.

错误:

W/BroadcastQueue: Background execution not allowed: receiving Intent { act=android.intent.action.PACKAGE_ADDED dat=package:my.great.package flg=0x4000010 (has extras) } to com.google.android.googlequicksearchbox/com.google.android.apps.gsa.googlequicksearchbox.GelStubAppWatcher
Run Code Online (Sandbox Code Playgroud)

```

我的待遇:

Intent myNotification = new Intent("services.notifications.Notification");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, (int) (Math.random() * Integer.MAX_VALUE), myNotification, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
alarmManager.setExact(AlarmManager.RTC_WAKEUP, day.getTimeInMillis(), pendingIntent);
Run Code Online (Sandbox Code Playgroud)

我的通知:

public class Notification extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        context.registerReceiver(this, new IntentFilter());

        try {
            WakeLock wakeLock = ((PowerManager) context.getSystemService(Context.POWER_SERVICE)).newWakeLock(1, "NotificationWakeLock");
            wakeLock.acquire(10000);

            try {
                scheduleNotification(context, intent);
            } finally {
                wakeLock.release();
            }
        } catch (NullPointerException e) {}
    }
}
Run Code Online (Sandbox Code Playgroud)

Jas*_*son 0

我通过添加前台服务解决了这个问题:

Intent test = new Intent(this, NotificationService.class);
startForegroundService(test);
Run Code Online (Sandbox Code Playgroud)

这将显示一条通知,告知我的应用程序正在前台运行。

并通过将其添加到我的服务的 oncreate 中:

startForeground(100, new NotificationCompat.Builder(this).build());
Run Code Online (Sandbox Code Playgroud)

  • 对我来说没有用, onReceive 方法甚至没有被调用 (2认同)