0

Hi I am working on a application where I am getting reminder details from user as reminder Date and reminder name and storing those in database. Now I want to know how can I start reminder through background service? Or Is there any other way if yes please tell me. What should I do? Please help me. Suggest something or tutorial will be great idea. Thanks in advance!

user3458918
  • 827
  • 1
  • 10
  • 15

1 Answers1

0

For this you will require two things

  1. Alarm manager: To set the time for notification or alarm (daily, weekly basis)
  2. Service: To launch your notification when alarm manager goes off

Do this in your activity class where you want to set the reminder

Intent myIntent = new Intent(this , NotifyService.class);     
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);

//get time from database and initialise the variables.
int minute;
int hour;

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.HOUR, hour);
calendar.set(Calendar.AM_PM, Calendar.AM);    //set accordingly
calendar.add(Calendar.DAY_OF_YEAR, 0);

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);

This will trigger Alarm each day at your set time.

Now, you should create a Service as NotifyService and put the following code in its onCreate():

@Override
public void onCreate() {
    NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    Notification notification = new Notification(R.drawable.notification_icon, "Notify Alarm strart", System.currentTimeMillis());
    Intent myIntent = new Intent(this , MyActivity.class);     
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
    notification.setLatestEventInfo(this, "Notify label", "Notify text", contentIntent);
    mNM.notify(NOTIFICATION, notification);
hunain60
  • 188
  • 3
  • 6