不在选定的时间发送通知,当我运行我的代码时,直接显示通知并显示错误以下是错误消息:E / NotificationManager:notifyAsUser:tag = null,id = 12345,user = UserHandle {0}我认为错误消息是由Build.VERSION.SDK_INT引起的,但在添加之后,错误消息仍然存在。
将所有这些放在onCreate下:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 13);
calendar.set(Calendar.MINUTE,9)
;
Intent intent = new Intent ();
intent.setAction("com.example.Broadcast");
PendingIntent contentIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// PendingIntent alarmIntent = PendingIntent.getBroadcast(this,0,intent,0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, contentIntent);
这是扩展。
public class wakeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
setNotification(context);
}
protected void setNotification(Context context){
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
String ChannelId = "12345";
int uniID = 12345;
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,ChannelId )
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle("Hi")
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setContentText("Please Rate.");
builder.setContentIntent(contentIntent);
// //向您的设备发送通知NotificationManager manager =(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId("com.myApp");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
"com.myApp",
"My App",
NotificationManager.IMPORTANCE_DEFAULT
);
if (manager != null) {
manager.createNotificationChannel(channel);
}
}
manager.notify(uniID, builder.build());
}
}
有人可以帮我这个吗?
你很困惑。
在你的代码中你打电话给NotificationManager.notify()
。这将立即显示Notification
。
你做:
Intent intent = new Intent(this, MainActivity.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this,0, intent,0);
这不行。你已经创建了一个PendingIntent
,它将通过广播使用Intent
发送给Activity
!你想要发生什么?你想要启动Activity
还是想要触发BroadcastReceiver
?
我想你想做的是如下:
Intent
创建一个BroadcastReceiver
,使用PendingIntent
将其包裹在getBroadcast()
中并将其传递给AlarmManager
,以便将来某个时候播放Intent
。extends BroadcastReceiver
的类。在onReceive()
创建Notification
并打电话给NotificationManager.notify()
发布Notification
。在Notification
你可以设置一个PendingIntent
打开你的Activity
,这样如果用户点击Notification
你的Activity
将被启动。要做到这一点,请调用PendingIntent.getActivity()
并传递包含Intent
的MainActivity.class
。