在片段中使用AlarmManager和BroadcastReceiver设置重复警报时遇到实际问题。使用Activity中的以下代码没有问题。当移动到Fragment时,BroadcastReceiver从不调用onReceive。
片段:
public void startAlarm(View view) {
Log.i(TAG, "startAlarm");
mAlarmMgr = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getActivity(), AlarmReceiver.class);
mAlarmIntent = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
mAlarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(),
60 * 1000,
mAlarmIntent);
}
public void cancelAlarm(View view) {
Log.i(TAG, "cancelAlarm");
// If the alarm has been set, cancel it.
if (mAlarmMgr!= null) {
mAlarmMgr.cancel(mAlarmIntent);
}
}
报警:
public class AlarmReceiver extends BroadcastReceiver {
private static final String TAG = AlarmReceiver.class.getName();
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "onReceive");
// For our recurring task, we'll just display a message
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}}
清单:
<receiver android:name=".alarms.AlarmReceiver">
</receiver>
好奇我可能会出错?我想,也许我没有在Manifest中正确注册接收器。
由于
答案 0 :(得分:1)
试试这个, 启动alaram
Intent intent = new Intent(getActivity(), Services.class);
Services.shouldContinue=true;
Calendar cal = Calendar.getInstance();
pintent = PendingIntent.getService(getActivity(), 0, intent, 0);
alarm = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
if (Services.shouldContinue) {
alarm.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), 5 * 1000, pintent);
}
取消alaram
Services.shouldContinue = false;
if (intent != null) {
getActivity().stopService(intent);
}
alarm.cancel(pintent);
答案 1 :(得分:0)
将接收器定义更改为以下
<receiver android:name=".alarms.AlarmReceiver"
android:enabled="true"
android:exported="true">
确保拨打startAlarm(View view)
来初始化闹钟。
答案 2 :(得分:0)
你可能想要的是更像这样的东西
private setRepeatingAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
long interval = 60 * 1000;
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
}
这里的主要区别在于使用AlarmManager.RTC_WAKEUP
vs AlarmManager.ELAPSED_REALTIME_WAKEUP
。
在5.0+警报的最小间隔内应注意的一件事是5分钟。