Как настроить уведомление с помощью диспетчера тревог - PullRequest
0 голосов
/ 27 сентября 2019

Я хочу создать уведомление после 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 Ответ

1 голос
/ 27 сентября 2019

Ваши строки не совпадают:

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

Кроме того, вам необходимо создать канал уведомлений, иначе уведомление не будет отображаться на Android 9 +

...