1 回答
TA贡献1864条经验 获得超2个赞
在 AndroidManifest.xml 中像这样注册你的接收器
<receiver
android:name="com.example.AlarmNotificationReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="com.example.AlarmNotificationReceiver" />
</intent-filter>
</receiver>
像这样设置你的意图并像这样设置警报:
Intent intent = Intent();
intent.setClass(context,AlarmNotificationReceiver.class);
intent.setAction("com.example.AlarmNotificationReceiver");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis(), pendingIntent);
setExact在设置的确切时间被调用。
请注意,在 Android Oreo 中,通知需要显示通知渠道。
像这样创建通知通道:
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel = new NotificationChannel("default","Default",NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
像这样创建通知:
Notification notification = new NotificationCompat.Builder(context, "default")
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle("It's time")
.setContentText("Time to training")
.setContentInfo("Info")
.build();
manager.notify(1, notification);
添加回答
举报