为什么我的 AlarmManager 不工作?
Why isn't my AlarmManager working?
我正在尝试发出一个警报,从现在开始的几秒内触发一个事件,一次,从 DialogFragment 中。
这里是相关代码,我放在onCreate():
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
Toast.makeText(c, "Rise and Shine!", Toast.LENGTH_LONG).show();
}
};
getActivity().registerReceiver(broadcastReceiver, new IntentFilter(ALARM_MANAGER_TAG) );
pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, new Intent(ALARM_MANAGER_TAG), 0 );
alarmManager = (AlarmManager)(getActivity().getSystemService( Context.ALARM_SERVICE ));
然后当我按下开始按钮时:
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timestampEnd, pendingIntent);
在这种情况下 timestampEnd = System.currentTimeMillis() + 10 * 1000;
,10 秒。
然后我覆盖了销毁:
@Override
public void onDestroy() {
alarmManager.cancel(pendingIntent);
getActivity().unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
然而,由于某种原因什么也没发生。
您正在传递 AlarmManager.ELAPSED_REALTIME_WAKEUP
,这意味着 AlarmManager
将在检查时间戳时使用 SystemClock.elapsedRealtime()
。由于您传递的是根据 System.currentTimeMillis()
计算得出的内容,您将不得不等待大约 47 年才能触发警报。
要么将您的第一个参数更改为 AlarmManager.RTC_WAKEUP
,要么将您的时间戳更改为根据 SystemClock.elapsedRealtime()
.
计算
我正在尝试发出一个警报,从现在开始的几秒内触发一个事件,一次,从 DialogFragment 中。
这里是相关代码,我放在onCreate():
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
Toast.makeText(c, "Rise and Shine!", Toast.LENGTH_LONG).show();
}
};
getActivity().registerReceiver(broadcastReceiver, new IntentFilter(ALARM_MANAGER_TAG) );
pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, new Intent(ALARM_MANAGER_TAG), 0 );
alarmManager = (AlarmManager)(getActivity().getSystemService( Context.ALARM_SERVICE ));
然后当我按下开始按钮时:
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timestampEnd, pendingIntent);
在这种情况下 timestampEnd = System.currentTimeMillis() + 10 * 1000;
,10 秒。
然后我覆盖了销毁:
@Override
public void onDestroy() {
alarmManager.cancel(pendingIntent);
getActivity().unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
然而,由于某种原因什么也没发生。
您正在传递 AlarmManager.ELAPSED_REALTIME_WAKEUP
,这意味着 AlarmManager
将在检查时间戳时使用 SystemClock.elapsedRealtime()
。由于您传递的是根据 System.currentTimeMillis()
计算得出的内容,您将不得不等待大约 47 年才能触发警报。
要么将您的第一个参数更改为 AlarmManager.RTC_WAKEUP
,要么将您的时间戳更改为根据 SystemClock.elapsedRealtime()
.