我正在使用AlarmManager
進行調度。我的鬧鐘已設置。但是這個警報不會調用BroadcastReceiver
來捕捉事件。我已經搜索了很多,但我還沒有找到任何解決問題的方法。我張貼我的代碼,請看一看,看看我是否缺少一些東西。報警管理器沒有激活廣播接收器?
AlarmManagerClass:
public class ScheduleMessageManager {
Context context;
PendingIntent sender;
AlarmManager am;
public ScheduleMessageManager(Context context) {
this.context = context;
}
public void addAlram(int scheduledMessageID, long scheduledTime) {
// Activate Broadcast Receiver to receive broadcasts
activateBroadcastReceiver();
//Calendar cal = Calendar.getInstance();
Intent intent = new Intent(context, AlarmReceiver.class);
// In reality, you would want to have a unique variable for the request
// code
intent.putExtra("scheduledMessageID", scheduledMessageID);
sender = PendingIntent.getBroadcast(context, scheduledMessageID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Get the AlarmManager service
am = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, scheduledTime, sender);
Log.e("In ScheduleMessageManage", "***** Alarm is set to the mmessage *****");
}
public void cancelPeriodicSchedule(PendingIntent sender) {
if (am != null) {
if (sender != null) {
am.cancel(sender);
sender.cancel();
}
}
// Deactivate Broadcast Receiver to stop receiving broadcasts
deactivateBroadcastreceiver();
}
private void activateBroadcastReceiver() {
PackageManager pm = context.getPackageManager();
ComponentName componentName = new ComponentName(context, AlarmReceiver.class);
pm.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Toast.makeText(context, "activated", Toast.LENGTH_LONG).show();
}
private void deactivateBroadcastreceiver() {
// TODO Auto-generated method stub
PackageManager pm = context.getPackageManager();
ComponentName componentName = new ComponentName(context, AlarmReceiver.class);
pm.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
Toast.makeText(context, "cancelled", Toast.LENGTH_LONG).show();
}
}
我AlarmReceiver:
public class AlarmReceiver extends BroadcastReceiver {
int pendingIntentID; // same as scheduledMessageID
@Override
public void onReceive(Context context, Intent intent) {
Log.e("In On Receive", "Alarm has Initiated Broadcast Receiver....");
if (intent.hasExtra("scheduledMessageID")) {
pendingIntentID = intent.getExtras().getInt("scheduledMessageID");
Intent sendMessageServiceIntent = new Intent(context, SendMessageService.class);
sendMessageServiceIntent.putExtra("pendingIntentID", pendingIntentID);
context.startService(sendMessageServiceIntent);
}
}
}
OnReceieve()
是永遠調用。
在我的Manifest.xml
<receiver
android:name="myPackage.AlarmReceiver"
android:enabled="true" >
</receiver>
我無法找出確實的問題出在哪裏。請幫我解決它。謝謝。!
你檢查的時間,是正確的?你是否在使用GregorianCalendar – 2013-03-07 09:42:23
是的,我認爲時間是正確的,因爲我也將它顯示在我的清單上,顯示正確的時間。 – 2013-03-07 09:43:46
聽起來很愚蠢,但你有沒有檢查過scheduleTime是未來? (這是觸發報警的絕對時間,而不是報警發生前經過的時間)。對不起,如果你知道這一點,並已檢查。 – 2013-03-07 09:45:03