使用AlarmManager重新安排IntentService - 忽略意图额外信息

时间:2012-10-09 11:46:45

标签: android alarmmanager intentservice

我有一个IntentService,最初是通过单击按钮启动的:

        Intent intent = new Intent(this, ProximityService.class);
        intent.putExtra("com.hybris.proxi.triggerTime", 5000l);
        PendingIntent pendingIntent = PendingIntent.getService(this,  0,  intent, 0);
        long trigger = System.currentTimeMillis() + (5*1000);
        alarmManager.set(AlarmManager.RTC_WAKEUP, trigger, pendingIntent);

这很好用。但后来我试图从intentservice中再次执行相同的intentservice。这里的想法是我可以改变下一个执行时间以节省电池。

@Override
protected void onHandleIntent(Intent intent) {
    Log.d("demo", "ProximityService... STARTING");
    Log.d("demo", "Intent has extra with key com.hybris.proxi.triggerTime" + intent.hasExtra("com.hybris.proxi.triggerTime"));

    long lastTriggerTime = intent.getLongExtra("com.hybris.proxi.triggerTime", -1);
    Log.d("demo", "Last trigger time: " + lastTriggerTime);

    alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    //trigger me again - TODO change this based on closeness to store
    //TODO does not work, somehow triggertime is not incremented
    if (lastTriggerTime < 50000)
    {
        long newTriggerTime = lastTriggerTime * 2;

        Intent serviceIntent = new Intent(this, ProximityService.class);
        serviceIntent.putExtra("com.hybris.proxi.triggerTime", (long)newTriggerTime);
        Log.d("demo","New triggerTime set in new intent is : " + serviceIntent.getLongExtra("com.hybris.proxi.triggerTime", -1));

        PendingIntent pendingIntent = PendingIntent.getService(this,  0,  serviceIntent, 0);
        long trigger = System.currentTimeMillis() + newTriggerTime;
        alarmManager.set(AlarmManager.RTC_WAKEUP, trigger, pendingIntent);
        Log.d("demo", "Alarm was set with trigger time " + newTriggerTime);
    } 
    else {
        Log.d("demo", "Not rescheduling alarm: lastTriggerTime is " + lastTriggerTime);
    }


    Log.d("demo", "ProximityService... DONE");

}

问题在于

intent.getLongExtra(“com.hybris.proxi.triggerTime”, - 1);

始终返回初始值5000 - 因此下一个警报不会在紧急触发时间内安排。不知何故,为新的触发时间设置额外的意图不起作用......

有什么想法吗?

1 个答案:

答案 0 :(得分:10)

您需要使用PendingIntent.FLAG_UPDATE_CURRENT

更改您的代码 PendingIntent pendingIntent = PendingIntent.getService(this, 0, serviceIntent, 0);  到

PendingIntent pendingIntent = PendingIntent.getService(this,
                        0,  serviceIntent, PendingIntent.FLAG_UPDATE_CURRENT);