java - 我的闹钟应用程序不会显示闹钟通知或播放闹钟声音?

标签 java android alarmmanager alarm

我正在使用 AlarmManager 来发出警报。我不确定为什么它不起作用,请随时索取更多代码。预先感谢您。

MainActivity.java

button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                    if (isChecked) {
                        alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                        Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTimeInMillis(System.currentTimeMillis());
                        int y = calendar.get(Calendar.YEAR);
                        int mon = calendar.get(Calendar.MONTH);
                        int d = calendar.get(Calendar.DAY_OF_MONTH);
                        if (ampm.equals("pm")){
                            h=h+12;
                        }
                        calendar.set(y, mon, d, h, m);
                        alarmIntent =PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
                        alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * intervalMinute, alarmIntent);
                    } else {
                        if (alarmMgr!=null) {
                            alarmMgr.cancel(alarmIntent);
                        }
                    }

没有错误。

最佳答案

setRepeating 相当于 API 级别 19+ 上的 setInexactRepeating。来自文档:

Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. Legacy applications whose targetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact.

您需要根据您的目标 API 级别调用 setsetExact 或(可能)setAlarmInfo,并手动安排重复警报。

此外,请仔细检查您设置下一个闹钟时间的逻辑,因为现在对我来说它看起来过于复杂。你可以这样做:

final Calendar c = Calendar.getInstance();
c.add(1, Calendar.DAY_OF_MONTH); //Just an example
alarmMgr.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);

我在 GitHub 上发布了一个闹钟应用程序,它也可能有用 ( link )。

关于java - 我的闹钟应用程序不会显示闹钟通知或播放闹钟声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57136763/

相关文章:

android - 将 JNIEnv 或上下文从 Java 传递给 Go

android - Google Play 游戏服务成就 Activity 立即结束

android - 如何从穿戴应用程序启动移动应用程序?

android - 如何在 android 中一次设置多个闹钟?

Android Notification & Alarmmanager - 时间不同

java - android:闹钟在某个特定时间间隔之间停止

java - 在ASM中能否获取putfield或putstatic指令的Field实例?

java - 通过 JDBC/ODBC/Microsoft Access 进行字符编码

java - 强制关闭膨胀 XML

java - 鼠标坐标查找器 GUI 无法正常运行