Search code examples
androidnotificationsandroid-pendingintentalarm

Set alarm from notification


I need to add an alarm to mobile's clock app for which I'm sending user a notification. When user clicks on notification a new alarm should be added with given time. Below is the code:

//Create intent
Intent alarmIntent = new Intent(AlarmClock.ACTION_SET_ALARM);
alarmIntent.putExtra(AlarmClock.EXTRA_MESSAGE, event.getEventName());
Calendar alarmTime = new GregorianCalendar();
alarmTime.setTime(new Date(event.getAlarmTime()));
alarmIntent.putExtra(AlarmClock.EXTRA_HOUR, alarmTime.get(Calendar.HOUR_OF_DAY));
alarmIntent.putExtra(AlarmClock.EXTRA_MINUTES, alarmTime.get(Calendar.MINUTE));
PendingIntent alarmPendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);

//Create and show notification
NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel("MyAppsAlarm",
        "MyAppsAlarmNotifications",
        NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Channel to show notifs");
mNotificationManager.createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(main.getApplicationContext(), "Zzzzz")
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("Alarm Helper")
        .setContentText(message)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setContentIntent(alarmPendingIntent);
mNotificationManager.notify(0, builder.build());

When I click on notification nothing happens. Notification stays as it is while the notification drawer closes automatically.

I tried to fire the intent using startActivity(alarmIntent); and it works as expected but from notification .setContentIntent(alarmPendingIntent); seems to be doing nothing.


Solution

  • If you want to set an alarm using AlarmClock.ACTION_SET_ALARM then you have to use PendingIntent.getActvity() instead of PendingIntent.getBroadcast(). AlarmClock.ACTION_SET_ALARM is an Activity ACTION.

    If you don't want the UI of the alarm clock to be shown, you can add this to the Intent:

    alarmIntent.putExtra(AlarmClock.EXTRA_SKIP_UI, true);