Search code examples
androidandroid-servicealarmmanagerandroid-pendingintentandroid-timepicker

AlarmManager not working with time picker


I have a Service.. I have to generate a notification at the time taken from time picker.. It is working with System.currentTimeMillis(), but not if I take the time from the time picker

Here is the time picker which i am showing on click of textView:

 tv.setOnClickListener(new OnClickListener() {
  @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub
  mcurrentTime = Calendar.getInstance();
  int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
  int minute = mcurrentTime.get(Calendar.MINUTE);
  TimePickerDialog mTimePicker;
  mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
  @Override
 public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
  timePicker.setIs24HourView(true);
  //tv.setText( selectedHour + " : " + selectedMinute);  
  mcurrentTime.set(Calendar.HOUR,selectedHour);
  mcurrentTime.set(Calendar.MINUTE,selectedMinute);
  mcurrentTime.set(Calendar.SECOND,0);
  // HERE I AM GETTING TIME FROM TIMEPICKER
  l= mcurrentTime.getTimeInMillis();
  tv.setText(String.valueOf(l));
  }
 }, hour, minute, true);//Yes 24 hour tim
  mTimePicker.setTitle("Select Time");
  mTimePicker.show();

  }
 });

Here is the code of button click, on this click i am starting service:

 Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
 int randomPIN = (int)(Math.random()*9000)+1000;
 pendingIntent = PendingIntent.getBroadcast(MainActivity.this, randomPIN, myIntent,pendingIntent.FLAG_ONE_SHOT);
 AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
 //HERE I am entering the time from time picker
 alarmManager.set(AlarmManager.RTC, l , pendingIntent);

Solution

  • Replace this:

    mcurrentTime.set(Calendar.HOUR, selectedHour);
    

    with this:

    mcurrentTime.set(Calendar.HOUR_OF_DAY, selectedHour);
    

    Calendar.HOUR is strictly for 12 hours.

    As per Documentation

    Field number for get and set indicating the hour of the morning or afternoon. HOUR is used for the 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12. E.g., at 10:04:15.250 PM the HOUR is 10.