我试图以这种方式处理它:在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)+"");
}
}
答案 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),通过拨打IntentService
从onReceive()
开始WakefulBroadcastReceiver.startWakefulService()
,在{{ 1}}并在完成后调用onHandleIntent()
。