Reputation: 197
This is my onclick() function.this will set target alarm
SA=(Button)findViewById(R.id.button1); SA.setOnClickListener(new OnClickListener() { @SuppressWarnings("deprecation") @Override public void onClick(View v) { showDialog(id); } }); } @Override protected Dialog onCreateDialog(int id1) { switch (id1) { case id: // set time picker as current time return new TimePickerDialog(this, timePickerListener, hour, min,false); } return null; } private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) { Calendar calnow=Calendar.getInstance(); calnow.setTimeInMillis(System.currentTimeMillis()); calnow.set(Calendar.HOUR_OF_DAY,selectedHour); calnow.set(Calendar.MINUTE,selectedMinute); calnow.set(Calendar.SECOND, 0); Intent intent=new Intent(getBaseContext(),alarm.class); PendingIntent pendingintent= PendingIntent.getBroadcast(getBaseContext(),0, intent, 0); AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, calnow.getTimeInMillis(),pendingintent); Toast.makeText(getBaseContext(), "alarm set", Toast.LENGTH_SHORT).show(); } };
public void onReceive(Context arg0, Intent arg1) { AlarmManager mgr = (AlarmManager)arg0.getSystemService(Context.ALARM_SERVICE); Toast.makeText(arg0,"Alarm Started.....", Toast.LENGTH_LONG).show();
Here problem is that I get both toasts "alarm set" and"alarm started" as soon as I click button to set alarm before reaching target alarm.
Upvotes: 8
Views: 2183
Reputation: 469
your fault is here. so do it like that
Calendar calnow=Calendar.getInstance()
calnow.set(Calendar.HOUR_OF_DAY,selectedHour);
calnow.set(Calendar.MINUTE,selectedMinute);
calnow.set(Calendar.SECOND, 0);
if (calnow.getTimeInMillis()< System.currentTimeMillis()) {
calnow.set(Calendar.DAY_OF_YEAR, 1)
}
Upvotes: 1
Reputation: 9870
the problem here is, that the value from TP seems to be the current time. It would be helpful if You show more of Your code. Let me give You an example for setting alarm time with a delay of 5 seconds. Please try out this one, it´s a dirty way, I just want to explain. This is what You did:
calnow.set(Calendar.HOUR_OF_DAY,TP.getCurrentHour());
calnow.set(Calendar.MINUTE,TP.getCurrentMinute());
alarmManager.set(AlarmManager.RTC_WAKEUP, calnow.getTimeInMillis(),pendingintent);
to get a delay of five seconds, change it to
alarmManager.set(AlarmManager.RTC_WAKEUP, calnow.getTimeInMillis()+5000,pendingintent);
like I said, this is only to show which value You have to set to alarmManager. It has to be the time in milliseconds, when You want to start the alarm. For this, You have to be sure to get the right values from Your TP. So, if You want us to help You, it will be a good way to show us the complete code
Upvotes: 0