1 回答

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
在 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>
像這樣設(shè)置你的意圖并像這樣設(shè)置警報(bào):
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在設(shè)置的確切時(shí)間被調(diào)用。
請注意,在 Android Oreo 中,通知需要顯示通知渠道。
像這樣創(chuàng)建通知通道:
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);
}
像這樣創(chuàng)建通知:
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);
添加回答
舉報(bào)