我必须按照以下代码调用 BroadcastReceiver:
public class WorkItemAlarmManager {
...
public void initAlarm(HelpMe helpMe, String delay,String period,WorkItem workItem){
//HelpMe = Activity
helpMe.registerReceiver(new WorkItemAlarmHandler() , new IntentFilter("WORK_ITEM_ALARM"));
Intent intent = new Intent("WORK_ITEM_ALARM");
intent.setClass(helpMe, WorkItemAlarmManager.class);
intent.putExtra("work_item", workItem);
PendingIntent mAlarmSender = PendingIntent.getService(helpMe, 0,intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
//System.out.println("START"+System.currentTimeMillis());
calendar.add(Calendar.SECOND, calcDelayMillis(delay));
//System.out.println("END"+calendar.getTimeInMillis());
AlarmManager am = (AlarmManager) helpMe.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), mAlarmSender);
}
...
}
和广播接收器:
public class WorkItemAlarmHandler extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
....
}
}
但是 WorkItemAlarmHandler 永远不会被调用。
更新:我首先尝试在清单中注册广播接收器。但这没有用:
<receiver
android:name="de.helpme.alarm.WorkItemAlarmHandler"
android:enabled="true"
android:label="WorkItemAlarmHandler" >
<intent-filter>
<action android:name="WORK_ITEM_ALARM" />
</intent-filter>
</receiver>
感谢您的回答:)。现在它可以工作了——但我还不知道哪个是正确的,因为我同时实现了两个答案。如果确定哪个是正确的,我将正确标记为答案。
更新: 我认为问题的原因是:
PendingIntent mAlarmSender = PendingIntent.getService(helpMe, 0,intent, 0);
使用此代码可以正常工作:
PendingIntent mAlarmSender = PendingIntent.getBroadcast(helpMe, 0, intent, 0);
再次感谢你的帮助!