AlarmManager 不适用于时间选择器

AlarmManager not working with time picker

我有一项服务。我必须在从时间选择器获取的时间生成通知。它正在使用 System.currentTimeMillis(),但如果我从时间选择器获取时间则不会[=13] =]

这是我在点击 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();

  }
 });

这里是按钮点击的代码,在这个点击上我开始服务:

 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);

您可以使用以下代码通过 Intent 过滤器进行服务调用。

尝试 setExact 而不是 set

set javadoc 中有一段:

Note: Beginning in API 19, the trigger time passed to this method is treated as inexact: the alarm will not be delivered before this time, but may be deferred and delivered some time later. The OS will use this policy in order to "batch" alarms together across the entire system, minimizing the number of times the device needs to "wake up" and minimizing battery use. In general, alarms scheduled in the near future will not be deferred as long as alarms scheduled far in the future.

替换为:

mcurrentTime.set(Calendar.HOUR, selectedHour);

有了这个:

mcurrentTime.set(Calendar.HOUR_OF_DAY, selectedHour);

Calendar.HOUR严格来说是12小时。

根据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.