正如标题所说,我的广播接收器从未被调用过。
我束手无策,我知道有 30..000 个关于此的帖子,我发誓我已经阅读了其中的大部分并尝试了十几件事,但我要么错过了一些明显的东西,要么遇到了一个奇怪的问题。
没有任何崩溃,没有错误或警告。
以下是我的清单的相关部分:
<receiver android:name=".AlertReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name=".AlertReceiver"/>
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="android.permission.USE_EXACT_ALARM" />
这是我的MainActivity中的创建方法:
private void startAlarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, FLAG_IMMUTABLE);
if (c.before(Calendar.getInstance())) {
c.add(Calendar.DATE, 1);
}
syncAlarm(this, c.getTimeInMillis(), alarmManager, pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Log.d("MainAcitivy", "Created Alarm")
}
private void syncAlarm(Context context, long time, AlarmManager am, PendingIntent pending) {
Intent intent = new Intent(this, AlertReceiver.class);
if (Build.VERSION.SDK_INT >= 23) {
// Wakes up the device in Doze Mode
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time, // time in millis
pending);
} else if (Build.VERSION.SDK_INT >= 19) {
// Wakes up the device in Idle Mode
am.setExact(AlarmManager.RTC_WAKEUP, time, pending);
} else {
// Old APIs
am.set(AlarmManager.RTC_WAKEUP, time, pending);
}
}
这是我的广播接收器:
public class AlertReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"AlertReceiver called", Toast.LENGTH_LONG).show();
Log.d("Broadcast Receiver", "Entered onReceive");
}
}
感谢您的宝贵时间。
编辑:好吧,事实证明它在技术上是有效的,但它似乎只有在我跳舞时才会触发,我还没有完全弄清楚在过了应该触发警报的时间后我在哪里锁定和解锁屏幕。如果我让应用程序保持打开状态,它不会触发。我想我一定是缺少一个设置。
好吧,我发现了问题:
注意:从 API 19 开始,所有重复警报都是不准确的。如果您的应用程序需要精确的交付时间,那么它必须使用一次性精确警报,并如上所述重新安排每次时间。 targetSdkVersion 早于 API 19 的旧应用程序将继续将其所有警报(包括重复警报)视为准确警报。
我尝试了一些精确的警报,效果很好,只需更深入地研究文档即可发现表面上的内容是谎言。