Android重复警报,每次打开时都会覆盖 self

标签 android android-alarms

我在应用程序启动时从 MainActivity 运行了以下警报。我想我已将其编程为在每次启动新应用程序时覆盖自身。但我发现很难测试。这是否确实会覆盖自身,或者如果我多次关闭和打开应用程序,我会收到很多警报吗?

如何测试我创建了多少个警报?

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent(this, AlarmBroadcastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        manager.setRepeating(AlarmManager.RTC_WAKEUP, 5000, 60000, pendingIntent);
    }

所以对于 PendingIntent.getBroadcast(Context context, int requestCode, Intent intent, int flags)

  • requestCode 是? (我假设为警报设置一个 ID,您可以用新警报覆盖它)
  • flags 做什么? (告诉闹钟如果新闹钟有相同的ID怎么办?)

最佳答案

是的,您可以覆盖它,因为每次创建 Activity 时您都使用相同的请求代码。 requestcode 是 PendingIntent.getBrodacast() 方法的第二个参数,其操作类似于您报警的 id,以便稍后更新它(例如取消它)。您可以使用此代码检查您的闹钟是否已设置:

boolean alarmUp = (PendingIntent.getBroadcast(context, 0, 
        new Intent("com.my.package.MY_UNIQUE_ACTION"), 
        PendingIntent.FLAG_NO_CREATE) != null);

但是你没有用你需要调用的代码设置闹钟:

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, 0 ,pendingIntent);

实际设置闹钟。

关于你的最后一个问题,有几个选项可以如何使用标志:

int FLAG_CANCEL_CURRENT Flag indicating that if the described PendingIntent already exists, the current one should be canceled before generating a new one.

int FLAG_IMMUTABLE Flag indicating that the created PendingIntent should be immutable.

int FLAG_NO_CREATE Flag> indicating that if the described PendingIntent does not already exist, then simply return null instead of creating it.

int FLAG_ONE_SHOT Flag indicating that this PendingIntent can be used only once.

int FLAG_UPDATE_CURRENT Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent.

关于Android重复警报,每次打开时都会覆盖 self ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43199095/

相关文章:

java - 在一定时间后更改变量

java - Android Force 类是最小类型

android - 每分钟更新一次的电池高效 android 小部件

如果当天的闹钟时间已经过去,android 会阻止立即触发闹钟服务

android - 来自 GIT 的闹钟 - 给出错误 - Android

android - 如何导航到不在返回堆栈上的父 Activity ?

android - Titanium SDK 在 Ubuntu 12.04 上无法识别 Titanium CLI、node、alloy 或 npm

java - @IdRes 的 Android 注解工作

android - 如何解决为 AlarmManager 设置唯一 ID 的问题?

android - 屏幕关闭(手机锁定)时,MediaPlayer(或铃声)不会开始播放