每次活动都会触发Android AlarmManager

时间:2014-07-09 17:40:56

标签: android alarm android-alarms

我有一项活动,使用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);

}

1 个答案:

答案 0 :(得分:1)

创建警报的代码位于onCreate()中,因此每次调用onCreate()时都会创建警报。您可以在首次创建警报时设置布尔标志,并仅在必要时设置警报。如果bundle不为null,只需确保将该boolean保存到bundle并在onCreate()中检索它。

有一个非常好的活动生命周期图here

在您的特定情况下,您应该了解系统经常调用onCreate()。例如,每当您旋转设备以更改其方向(例如,从纵向到横向)时,都会调用onCreate()(除了其他生命周期方法)。这些方法按特定顺序和特定时间调用,因此您需要围绕该生命周期进行编程。