How to repeat notification daily on specific time in android through background service

前端 未结 2 367
刺人心
刺人心 2020-12-01 00:57

Hi I am working on application where I have set the notification on user entered date and time through background service. Now I want to set notification/alarm daily at 6 p

2条回答
  •  有刺的猬
    2020-12-01 01:35

    First set the Alarm Manager as below

     Calendar calendar = Calendar.getInstance();
     calendar.set(Calendar.HOUR_OF_DAY, 18);
     calendar.set(Calendar.MINUTE, 30);
     calendar.set(Calendar.SECOND, 0);
     Intent intent1 = new Intent(MainActivity.this, AlarmReceiver.class);
     PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0,intent1, PendingIntent.FLAG_UPDATE_CURRENT);
     AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
     am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    

    Create an Broadcast Receiver Class "AlarmReceiver" in this raise the notifications when onReceive

    public class AlarmReceiver extends BroadcastReceiver{
    
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
    
            long when = System.currentTimeMillis();
            NotificationManager notificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
    
            Intent notificationIntent = new Intent(context, EVentsPerform.class);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                    notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    
    
            Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    
            NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
                    context).setSmallIcon(R.drawable.applogo)
                    .setContentTitle("Alarm Fired")
                    .setContentText("Events to be Performed").setSound(alarmSound)
                    .setAutoCancel(true).setWhen(when)
                    .setContentIntent(pendingIntent)
                    .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
            notificationManager.notify(MID, mNotifyBuilder.build());
            MID++;
    
        }
    
    }
    

    and in the manifest file, register receiver for the AlarmReceiver class:

    
    

    No special permissions are required to raise events via alarm manager.

提交回复
热议问题