为什么每日通知无法在Android系统上运行?

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

我想每天显示通知。但是我的代码没有在指定的时间显示通知。我的代码如下所示。

MainActivity.java

showNotifBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

            Calendar calendar=Calendar.getInstance();
            calendar.set(Calendar.HOUR,20);
            calendar.set(Calendar.MINUTE,21);
            calendar.set(Calendar.SECOND,55);

            Intent intent=new Intent(MainActivity.this,MyReceiver.class);
            PendingIntent pendingIntent=PendingIntent.getBroadcast(MainActivity.this,0,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");

    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);
    NotificationManager nm = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);

    NotificationCompat.Builder builder=new NotificationCompat.Builder(context,"0");
    builder.setContentTitle("Hello there");
    builder.setContentIntent(pendingIntent);
    builder.setContentText("Check new events");
    builder.setSmallIcon(android.R.drawable.star_on);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannel channel=new NotificationChannel("0","0",NotificationManager.IMPORTANCE_HIGH);
        nm.createNotificationChannel(channel);
        builder.setChannelId("0");
    }

    nm.notify(0,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.