我有下面的代碼來調用廣播接收器:廣播接收器不叫
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永遠不會被調用。
更新: 我試着首先在清單中註冊BroadcastReceiver。但是這並不奏效:
<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);
你的幫助再次感謝!
您是否在manifest.xml中註冊過該代碼。 –