未使用广播接收器显示通知

问题描述 投票:0回答:1

我想每天显示通知。但是我的代码一次都没有显示。

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"/>

在指定时间不显示任何单个通知有什么问题?

我的规格:

  • Android Studio 3.6.2
  • 目标SDK:29,最小值:24
  • 等级5.6.4
android android-intent broadcastreceiver android-notifications alarmmanager
1个回答
0
投票

您应将通知通道设置为NotificationManagerNotificationBuilder。在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);
}
© www.soinside.com 2019 - 2024. All rights reserved.