简体   繁体   中英

How to send a Notification at a specific time?

I would like to send a notification at a specific time. Below is my code. Right now, I only get a notification when I start the app, but I do not get a notification at the specified time. Could you help me understand what I am doing wrong.

 NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("My notification")
            .setContentText("Trainieren sie jetzt!")
            .setAutoCancel(true);
    Intent resultIntent = new Intent(this, MainActivity2.class);

    AlarmManager alarmManager =(AlarmManager)getSystemService(ALARM_SERVICE);



    PendingIntent resultPendingIntent =
        PendingIntent.getActivity(
        this,
        0,
        resultIntent,
        PendingIntent.FLAG_UPDATE_CURRENT);


   Calendar cal = Calendar.getInstance();
   cal.set(Calendar.HOUR_OF_DAY, 12);
   cal.set(Calendar.MINUTE, 54);
   alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 24*60*60*1000, resultPendingIntent);



    mBuilder.setContentIntent(resultPendingIntent);
    int mNotificationId = 001;
    NotificationManager mNotifyMgr = 
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mNotifyMgr.notify(mNotificationId, mBuilder.build());

Thanks for helping!

You need to add:

@Override
public void onReceive(Context context, Intent intent) {
    //  Toast.makeText(MainActivity.con, "Hello from alarm", 1).show(); 


    // System.out.println("Hello from Alarm");
    context.startService(new Intent(context, NotificationService.class));

}

In the above example I am directing the process to my Service class to process my notification, managing wake locks and background service implementation. If you are not implementing a Service you can just display your notifications in the onRecieve method.

Please have a look here it has a complete implementation of the Alarm Class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM