I'm trying to set up a one-time alarm that will wake up my app and then deliver a notification to the user.
I'm setting the alarm for 1 minute in the future, but my broadcast receiver is never called.
This is how I'm scheduling the AlarmManager
and building the Notification
:
private void scheduleNotification(Date notificationdate) {
Log.d("PSBMF", "scheduling notification at "+notificationdate);
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+AppController.statewidephone));
PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 0, intent, 0);
String notificationmessage = "Test Message";
String channelid = "Channel Id";
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getActivity(), channelid)
.setSmallIcon(R.drawable.ic_warning_black_36dp)
.setContentTitle("Notification Title")
.setContentText("Notification Content")
.setStyle(new NotificationCompat.BigTextStyle().bigText("Notification Content"))
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentIntent(pendingIntent)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setDefaults(Notification.DEFAULT_ALL)
;
Notification notification = mBuilder.build();
Intent notificationIntent = new Intent(mActivity, NotificationPublisher.class);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, 1);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(mActivity, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
long notificationTimeInMillis = notificationdate.getTime();
AlarmManager alarmManager = (AlarmManager)mActivity.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, notificationTimeInMillis, pendingAlarmIntent);
}
My NotificationPublisher.class
looks like this:
public class NotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";
public void onReceive(Context context, Intent intent) {
Log.d("NP", "NOTIFICATION RECEIVED: "+context);
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
}
}
and I've registered my NotificationPublisher/BroadcastReceiver
by putting this inside the <application/>
tag of my manifest:
<receiver android:name=".NotificationPublisher"/>
What else am I missing? Why won't my Alarm get triggered and call the onReceive
method?
I think I figured out my problem:
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, notificationTimeInMillis, pendingAlarmIntent);
should be
alarmManager.set(AlarmManager.RTC_WAKEUP, notificationTimeInMillis, pendingAlarmIntent);