无法使用 AlarmManager 修复通知的 IntentService

Can't fix IntentService for notification with AlarmManager

我正在尝试这样处理:在BroadcastReceiver开始AlarmManager重复动作,它会发送意图到IntentService,服务写入日志。现在我从日志中看到,BroadcastReceiver 接收到意图,启动 AlarmManager,但 IntentService 从未触发。这里有什么问题吗?

清单:

<receiver android:name=".wakefullBroadcastReciever.SimpleWakefulReciever" android:enabled="true" android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <action android:name="START"/>
            </intent-filter>
        </receiver>

        <service
            android:name=".wakefulService.NotificationWakefulIntentService"
            android:enabled="true">
            <intent-filter>
                <action android:name="NOTIFY_INTENT" />
            </intent-filter>
        </service>

唤醒接收者:

public class SimpleWakefulReciever extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (!App.isRunning) {
            Log.d("wakefull", "start");
            Intent startIntent = new Intent(context, NotificationWakefulIntentService.class);
            startIntent.setAction(Utils.NOTIFY_INTENT);
            PendingIntent startPIntent = PendingIntent.getBroadcast(context, 0, startIntent, 0);
            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            am.setRepeating(AlarmManager.RTC_WAKEUP,
                    SystemClock.elapsedRealtime() + 3000, 5000, startPIntent);
            App.isRunning = true;
        }
    }
}

意向服务:

public class NotificationWakefulIntentService extends IntentService {

    public NotificationWakefulIntentService() {
        super("NotificationWakefulIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d("time",(System.currentTimeMillis()/1000)+"");
    }
}

您正在定义显式 Service Intent,但调用 getBroadcast() 而不是 getService()

更改以下内容:

PendingIntent startPIntent = PendingIntent
    .getBroadcast(context, 0, startIntent, 0);

为此:

PendingIntent startPIntent = PendingIntent
    .getService(context, 0, startIntent, 0);

此外,这不是 WakefulBroadcastReceiver 的工作方式。它是一个助手 class,其目的是提供一个 WakeLock,直到您的 Service 完成它的工作。

通过简单地扩展 WakefulBroadcastReceiver,您将一事无成,无论如何在 onReceive() 期间保证 WakeLock

在下面回答您的评论:

你应该设置一个准确的闹钟,每小时触发一次(查看 this answer),通过调用 WakefulBroadcastReceiver.startWakefulService()onReceive() 开始你的 IntentService,做你的事情onHandleIntent() 并在完成后调用 WakefulBroadcastReceiver.completeWakefulIntent()