Android 安卓设置来自碎片的警报
在片段中使用AlarmManager和BroadcastReceiver设置重复报警时存在实际问题。活动中的以下代码没有问题。当移动到片段时,BroadcastReceive从不调用onReceive 片段:Android 安卓设置来自碎片的警报,android,android-fragments,broadcastreceiver,alarmmanager,Android,Android Fragments,Broadcastreceiver,Alarmmanager,在片段中使用AlarmManager和BroadcastReceiver设置重复报警时存在实际问题。活动中的以下代码没有问题。当移动到片段时,BroadcastReceive从不调用onReceive 片段: public void startAlarm(View view) { Log.i(TAG, "startAlarm"); mAlarmMgr = (AlarmManager) getActivity().getSystemService(Context.ALA
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>
只是好奇我可能会错在哪里?我在想,也许我没有在舱单上正确注册接收人
谢谢将您的接收器定义更改为以下
<receiver android:name=".alarms.AlarmReceiver"
android:enabled="true"
android:exported="true">
确保您正在调用
startAlarm(视图)
来初始化报警。您可能想要的是类似这样的东西
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\u唤醒
与AlarmManager.eassed\u REALTIME\u唤醒
在5.0+版本中,有一件事你应该注意,闹钟的最小间隔是5分钟。试试这个,
启动阿拉姆
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);
}
取消阿拉姆
Services.shouldContinue = false;
if (intent != null) {
getActivity().stopService(intent);
}
alarm.cancel(pintent);
默认情况下,
receiver
元素是enabled=true
,因此这是冗余的。此外,您不应该导出您的广播接收器
,除非您打算让设备上的其他应用程序呼叫您的接收器。谢谢。我尝试过这个,也尝试过使用android的完整包名:name。还是不走运,谢谢。也尝试过这种方法,并尝试过不精确和间隔重复。已尝试RTC_唤醒和已用_实时_唤醒以及更长和更短的间隔。还是不走运。正如我前面提到的,当从活动中调用时,所有代码都能正常工作。当我将start和cancel方法移动到片段时,会调用这些方法,但不会设置报警。