我有一个 Activity 使用 AlarmManager
创建一个应该每 3 分钟响一次的闹钟。它在应用程序关闭时执行,但是当您打开应用程序并且一旦您开始转到应用程序的不同方面时,就会在每个 Activity 加载时调用警报 onReceive() 方法!
如何停止该功能?
我希望闹钟每 3 分钟响一次
这是我的广播接收器:
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Testing...", Toast.LENGTH_SHORT).show();
}
这是我的 setalarm 方法(在 MainActivity onCreate 中)
public void startAlarmManager()
{
Intent dialogIntent = new Intent(getBaseContext(), AlarmReceiver.class);
alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
pendingIntent = PendingIntent.getBroadcast(this, 0, dialogIntent,PendingIntent.FLAG_CANCEL_CURRENT);
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), 180000, pendingIntent);
}
最佳答案
创建警报的代码在 onCreate() 中,因此每次调用 onCreate() 时都会创建警报。您可以在第一次创建警报时设置一个 bool 标志,并且只在必要时设置警报。只需确保将该 bool 值保存到包中,如果包不为空,则在 onCreate() 中检索它。
有一个非常好的 Activity 生命周期图 here .
在您的特定情况下,您应该了解系统经常调用 onCreate()
。例如,每当您旋转设备以更改其方向(例如,从纵向到横向)时,都会调用 onCreate()
(以及其他生命周期方法)。这些方法在特定时间按特定顺序调用,因此您需要“围绕”该生命周期进行编程。
关于Android AlarmManager 在每个 Activity 上触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24660405/