无法使用AlarmManager修复IntentService以进行通知

时间:2016-10-22 08:01:45

标签: android android-intent android-pendingintent android-broadcastreceiver android-intentservice

我试图以这种方式处理它:在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>

WakefulReciever:

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

IntentService:

public class NotificationWakefulIntentService extends IntentService {

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

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

1 个答案:

答案 0 :(得分:0)

您定义的是明确的Service Intent,但是调用getBroadcast()代替getService()

更改以下内容:

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

对此:

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

此外,这不是WakefulBroadcastReceiver的工作方式。它是一个帮助类,其目的是在WakeLock完成其工作之前提供Service

只需延长WakefulBroadcastReceiver即可获得任何结果,WakeLock无论如何都可以保证onReceive()

要回答以下评论:

您应该设置一个确切的闹钟,每小时开出一次(查看this answer),通过拨打IntentServiceonReceive()开始WakefulBroadcastReceiver.startWakefulService(),在{{ 1}}并在完成后调用onHandleIntent()