问题
I need to display a notification daily at particular time (for example: 4.25PM). I am using AlarmManager
and Notification
. I set the alarm on landing page of the application. I also have implemented the BroadcastReceiver
for it.
Code to set the alarm:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 16);
calendar.set(Calendar.MINUTE, 25);
calendar.set(Calendar.SECOND, 0);
Intent notificationmassage = new Intent(getApplicationContext(),Notificationmassage.class);
//This is alarm manager
PendingIntent pi = PendingIntent.getService(this, 0 , notificationmassage, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pi);
This is the broadcast receiver
public class Notificationmassage extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
showNotification(context);
}
private void showNotification(Context context) {
Log.i("notification", "visible");
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, Notificationmassage.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("xyz")
.setContentText("It will contain dummy content");
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
What is wrong with this approach?
回答1:
Add reciever to Manifest.xml if you don't do this before.
<receiver android:name="org.yourapp.Notificationmassage"></receiver>
in application section
<application>
....
<receiver android:name="org.yourapp.Notificationmassage"></receiver>
</application>
If you already do that, please edit your question and show your Manifest.xml
来源:https://stackoverflow.com/questions/26037211/show-notification-at-particular-time-with-alarmmanager