我正在尝试设置每天上午8点的闹钟,以便它可以显示一些通知 这是我设置闹钟的方法:
public static void scheduleAlarm(Context context) {
PackageManager pm = context.getPackageManager();
ComponentName receiver = new ComponentName(context, DeviceBootReceiver.class);
Intent alarmIntent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//region Enable Daily Notifications
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
// if notification time is before selected time, send notification the next day
if (calendar.before(Calendar.getInstance())) {
calendar.add(Calendar.DATE, 1);
}
if (manager != null) {
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
manager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
}
//To enable Boot Receiver class
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
我已为android O设置了频道,仍然没有通知。 有人可以在下面的代码中说明问题所在吗? 警报接收器类别以显示通知:
public class AlarmReceiver extends BroadcastReceiver {
@Overridepublic void onReceive(Context context, Intent intent) {
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingI = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
"Daily Notification",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Daily Notification");
if (nm != null) {
nm.createNotificationChannel(channel);
}
}
NotificationCompat.Builder b = new NotificationCompat.Builder(context, "default");
b.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("{Time to watch some cool stuff!}")
.setContentTitle("My Cool App")
.setContentText("Time to watch some cool stuff!")
.setContentInfo("INFO")
.setContentIntent(pendingI);
}}