Search code examples
androidalarmmanagerandroid-notificationsandroid-alarms

alarm manager android not working


The alarm manager does not work no matter what.

This is my main activity which calls the function to set the alarm on click. Extra code has not been shown.

    public void setAlarm() {
        Log.i("alarm", "Here");
        Long alertTimep = new GregorianCalendar().getTimeInMillis() + 5;
        Intent intent = new Intent(this, AlertReciever.class);
        AlarmManager alarmManager = (AlarmManager)
getSystemService(ALARM_SERVICE);
        PendingIntent pi = PendingIntent.getBroadcast(this,1,intent,PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.set(AlarmManager.RTC_WAKEUP, alertTimep, pi);
    }

This is my AlertReciever class.

    public class AlertReciever extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        showNotification(context);
        Log.i("alarm", "Here1");
    }

    public void showNotification(Context context) {
        Log.i("alarm", "Here2");
        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        PendingIntent pIntent = PendingIntent.getActivity(context, 0, new Intent(context, NotificationReceiver.class), 0);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                .setContentTitle("Hello")
                .setContentText("How are You")
                .setSmallIcon(R.drawable.ic_menu)
                        //.setContentIntent(pIntent)
                        //.addAction(R.drawable.ic_edit, "View", pIntent)
                .setSound(soundUri)
                        //.addAction(0, "Remind", pIntent)
                .setAutoCancel(true);
        mBuilder.setContentIntent(pIntent);

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, mBuilder.build());
    }

}

The basic idea is to schedule a notification to be generated at a given date,for testing purposes i have selected 5 seconds/milliseconds as of now.

The problem is that the alert receiver class does not get called nor does the app crash so i am unable to figure out where the fault is.I do not get any notification.


Solution

  • <receiver android:name="atsystems.cal.AlertReciever" />
    

    That was missing from my manifest file,after adding that everything worked fine. For anyone else looking at this code you also need alarm permissions in the manifest file.

    <uses-permission android:name="com.android.alarm.permission.SET_ALARM" />