【问题标题】:Android AlarmManager triggered on every activityAndroid AlarmManager 在每个活动上触发
【发布时间】:2014-07-09 17:40:56
【问题描述】:

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

}

【问题讨论】:

    标签: android alarm android-alarms


    【解决方案1】:

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

    有一张非常漂亮的Activity生命周期图here

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多