android - Android Studio AlarmManager 在特定时间没有运行
问题描述
这是警报管理器的代码:
protected void alarmInit(){
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 25);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this, SampleBootReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, alarmIntent, 0);
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
}
这是广播类:
public class SampleBootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_LONG).show();
intent = new Intent(context, NotificationService.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context)
// Set Icon
.setSmallIcon(R.drawable.icono)
// Set Ticker Message
.setTicker("message")
// Set Title
.setContentTitle("asdf")
// Set Text
.setContentText("message")
// Add an Action Button below Notification
// Set PendingIntent into Notification
.setContentIntent(pIntent)
// Dismiss Notification
.setAutoCancel(true);
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
// Build Notification with Notification Manager
notificationmanager.notify(0, builder.build());
}
}
}
}
但是在设定的时间我没有收到任何消息(我没有看到带有 Hello 字样的 Toast 消息)。此外,在 Manifest XML 中,我在应用程序标签中设置:
<receiver android:name=".Home$SampleBootReceiver"
android:enabled="false"
tools:ignore="Instantiatable">
SampleBootReceiver 类是 Home 类中的公共类
你能帮我解决这个问题吗?提前致谢
解决方案
您正在使用setInexactRepeating
,因此操作系统将决定何时触发警报。操作系统尝试将警报组合在一起以节省电池。
从 API 19 (Build.VERSION_CODES.KITKAT) 开始,警报传递是不准确的:操作系统将切换警报以最大程度地减少唤醒和电池使用。有新的 API 来支持需要严格交付保证的应用程序;参见 setWindow(int, long, long, android.app.PendingIntent) 和 setExact(int, long, android.app.PendingIntent)。targetSdkVersion 早于 API 19 的应用程序将继续看到以前的行为,即所有警报都在请求时准确传递。
https://developer.android.com/reference/android/app/AlarmManager
推荐阅读
- swift - 以编程方式 Init 与 dequeueForReusableIdentifier 用于表视图单元格
- angular - highcharts x轴不规则日期间隔问题
- vb.net - BC30456 Visual Basic
- http - 可能的竞争条件 使用 http2 实现
- r - R:风数据的 gDistance 转换函数
- python - 从 dict 更新 pandas df
- python - 拆分字典项
- c++ - 无法推断成员函数包装器的返回类型
- python - 循环遍历 SQL 数据并使用 Python 与自身进行比较
- javascript - 是否可以从继承的工厂方法中通用地实例化 JS 类类型?