Uzair Ahmed
Uzair Ahmed

Reputation: 33

How to set notification using alarm manager

I want to generate notification after 10 seconds of pressing a button in my main activity I have tried many method but not get notification

Here is the code in my main class

     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);

        }
    });

And AlertReceiver class

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());
    }

Upvotes: 0

Views: 578

Answers (1)

Lev Leontev
Lev Leontev

Reputation: 2615

Your strings don't match:

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

Also, you have to create a notification channel, or else the notification won't be shown on Android 9+

Upvotes: 1

Related Questions