【问题标题】:Android: Setting up a periodical alarm with AlarmManagerAndroid:使用 AlarmManager 设置定期警报
【发布时间】:2023-04-03 16:15:01
【问题描述】:

在我的应用程序中,我需要在数据库中添加一行并同时设置一个警报事件,以便每天在其中一个数据库列中指定的时间重复。我已经有一些代码,但它不会在指定时间触发警报事件。这是我的代码:

public class Add_reminder extends Activity {
    AlarmManager am;
    int hours, minutes;
    REMIND_DB db;
    Calendar calendar;
    Cursor cursor;
    Button button;

    public void onCreate(Bundle savedInstanceState) {
        //The usual code in the beginning of onCreate

        //I load db from extended Application class as global since i use it in more
        //Activities. Ints hours and minutes is set by user interaction

        calendar = Calendar.getInstance();
        am = (AlarmManager) getSystemService(ALARM_SERVICE);

        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                db.open();
                db.insertReminder( -- parameters for database --);
                cursor = db.getAllReminders();
                cursor.moveToLast();
                calendar.set(Calendar.HOUR, hours);
                calendar.set(Calendar.MINUTE, minutes);
                Intent intent = new Intent(Add_reminder.this, ReminderAlarm.class);
                intent.putExtra("id_of_db_row", cursor.getInt(0));
                PendingIntent pi =  PendingIntent.getActivity(Add_reminder.this,
                    cursor.getInt(0), intent, PendingIntent.FLAG_CANCEL_CURRENT);
                am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                    24*3600*1000, pi);
                db.close()
            } 
        });
    }
}

数据库已正确更新,但 ReminderActivity 从未在指定时间启动。我不知道有什么问题。我看到了一些使用 BroadcastReceiver 的示例代码,而不是使用 PendingIntent 直接启动 Activity,但这也应该有效,对吧?有谁知道可能出了什么问题?

我的第二个问题是,当我想从不同的 Activity 添加或删除一些警报时,我是否需要相同的 AlarmManager 实例,还是我只是在我需要的每个 Activity 中声明另一个 AlarmManager?

谢谢!

【问题讨论】:

    标签: android alarmmanager android-pendingintent


    【解决方案1】:

    您应该使用广播接收器来发出警报,然后启动一个服务来完成实际工作。广播接收器不应通过冗长的操作(例如写入数据库)阻塞 UI 线程。此外,“一天一次”的闹钟可能会有问题:如果用户重启手机:注册的闹钟将会丢失。您需要:

    • 保存警报应该运行的时间,例如 SharedPreferecnes
    • 手机开机时重新注册闹钟(接收 BOOT_COMPLETED 广播)
    • 不要使用setRepeating(),而是让每个警报都记录下一个

    使用较短的时间(1 或 2 分钟)进行测试也有帮助。

    至于AlarmManager实例,它是一个系统服务,你不需要关心你使用的是什么实例。只需使用getSystemService()获取它

    【讨论】:

    • 今天早上看手机的时候,发现想要的Activity已经启动了!似乎问题是我为它设置的时间(而不是使用 HOUR_OF_DAY 来表示 24 格式,我使用 HOUR 表示 12 格式,所以提醒会在 12 小时后提醒自己)。我的主要活动中有一段代码,在活动启动后只执行一次。我可以使用数据库中的数据在那里重新注册我的警报吗?如果用户只重新启动应用程序而不是手机本身,它会取代我的警报吗?或者它只是重复。谢谢。
    • Progress :) 尽管如此,让活动突然出现通常是个坏主意。正如我所说,使用广播接收器和服务。如果您需要用户交互,请发布通知并让用户启动活动。如果您使用等效的PendingIntent,警报将被覆盖,而不是重复。
    • 帮了大忙,谢谢 :) 我将使用广播接收器,正如你所说,这个时间问题更直接:)
    • 为什么不使用 setRepeating?在 BOOT_COMPLETED 将设置警报,然后在第一次之后将继续定期重复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多