我想每天显示通知。但是我的代码一次都没有显示。
MainActivity.java
showNotifBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i("app","clicked");
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.HOUR,17);
calendar.set(Calendar.MINUTE,24);
calendar.set(Calendar.SECOND,01);
Intent intent=new Intent(MainActivity.this,MyReceiver.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(MainActivity.this,100,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
}
});
MyReceiver.java
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("app","onReceive called");
NotificationManager manager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent1=new Intent(context,MainActivity.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent=PendingIntent.getActivity(context,100, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder=new NotificationCompat.Builder(context,"")
.setContentIntent(pendingIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("HBD")
.setContentText("HAPPY BIRTHDAY")
.setAutoCancel(true);
manager.notify(100,builder.build());
}
}
Manifest.xml
<receiver android:name=".MyReceiver"/>
在指定时间不显示任何单个通知有什么问题?
我的规格:
您应将通知通道设置为NotificationManager
和NotificationBuilder
。在manager.notify(100,builder.build());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "your_channel_id";
NotificationChannel channel = NotificationChannel(
channelId,
"Kristiana's Channel",
NotificationManager.IMPORTANCE_HIGH);
//Here set this channel to your NoficiationManager and Notification Builder
manager.createNotificationChannel(channel);
builder.setChannelId(channelId);
}