如何使用警报管理器设置通知

时间:2019-09-27 10:45:44

标签: java android notifications alarmmanager android-pendingintent

我想在主要活动中按下按钮10秒钟后生成通知 我尝试了很多方法,但没有收到通知

这是我主类中的代码

     btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            long when = System.currentTimeMillis() + 10000L;

            AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(this, AlertReceiver.class);
            intent.putExtra("myAction", "mDoNotify");
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
            am.set(AlarmManager.RTC_WAKEUP, when, pendingIntent);

        }
    });

和AlertReceiver类

if(intent.getStringExtra("myAction") != null &&
            intent.getStringExtra("myAction").equals("notify")){
        NotificationManager manager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.ic_launcher_background)
                //example for large icon
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
                .setContentTitle("my title")
                .setContentText("my message")
                .setOngoing(false)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setAutoCancel(true);
        Intent i = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent =
                PendingIntent.getActivity(
                        context,
                        0,
                        i,
                        PendingIntent.FLAG_ONE_SHOT
                );
        // example for blinking LED
        builder.setLights(0xFFb71c1c, 1000, 2000);
        //builder.setSound(yourSoundUri);
        builder.setContentIntent(pendingIntent);
        manager.notify(12345, builder.build());
    }

1 个答案:

答案 0 :(得分:1)

您的字符串不匹配:

intent.putExtra("myAction", "mDoNotify");
<...>
if(intent.getStringExtra("myAction") != null &&
        intent.getStringExtra("myAction").equals("notify")){

此外,您必须创建一个通知频道,否则该通知将不会在Android 9+上显示