如何为选定的日期和时间设置闹钟?

问题描述:

我从哪里可以设置从日期选取器和时间选择在一次时间和日期验证码:如何为选定的日期和时间设置闹钟?

private void dialoguetime() { 

    final Dialog dialog = new Dialog(this); 
    dialog.setContentView(R.layout.custom_dialogue); 
    dialog.setCancelable(true); 
    dialog.setTitle("This is Dialog 1"); 
    dialog.show(); 

    TimePicker time_picker = (TimePicker) dialog 
      .findViewById(R.id.timePicker1); 
    hours = time_picker.getCurrentHour(); 
    minute = time_picker.getCurrentMinute(); 
    time_picker.setOnTimeChangedListener(new OnTimeChangedListener() { 
     public void onTimeChanged(TimePicker view, int hourOfDay, 
       int minutes) { 
      // TODO Auto-generated method stub 
      // Toast.makeText(CustomDialog.this, 
      // "hourOfDay = "+hourOfDay+"minute = "+minute , 1000).show(); 
      hours = hourOfDay; 
      minute = minutes; 
     } 
    }); 

    final DatePicker date_picker = (DatePicker) dialog 
      .findViewById(R.id.datePicker1); 
    Button btn = (Button) dialog.findViewById(R.id.button2); 
    btn.setOnClickListener(new OnClickListener() { 

     public void onClick(View arg0) { 
      // TODO Auto-generated method stub 



      xDate = date_picker.getYear() + "-"+ (date_picker.getMonth() + 1) + "-"+ date_picker.getDayOfMonth() + " " + hours+ ":" + minute + ":00"; 
      Toast.makeText(
        getApplicationContext(), 
        xDate, Toast.LENGTH_LONG) 
        .show(); 
      dialog.cancel(); 
     } 

    } 

    ); 

} 

由此我可以得到一个字符串作为这样yyyy-mm-dd hh:mm:ss日期格式,现在我想向该选定时间的用户发出警报(作为警报)。我为此使用了闹铃管理器,但它不允许我选择该日期?

我该怎么做?

+0

请发布您的报警管理器代码。 – Tushar 2012-07-26 21:26:59

+0

我是alerm经理的开工人员,我使用的报警管理器在另一个项目中,每隔15分钟发送一次短信,但我知道不会在这里工作 – Reyjohn 2012-07-26 21:31:27

如果你看一下AlarmManager的API(http://developer.android.com/reference/android/app/AlarmManager.html),你可以看到,该方法

set() 

需要下列参数:

public void set (int type, long triggerAtMillis, PendingIntent operation) 

其中

int type = One of ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC or RTC_WAKEUP. 
long triggerAtMillis = time in milliseconds that the alarm should go off, using the appropriate clock (depending on the alarm type). 
PendingIntent operation = Action to perform when the alarm goes off 

所以basicly你应该做的,是让日之间的时间e选定的日期(DateFormat.parse()来解析日期格式的字符串)和当前日期。类似这样的:

Date now = new Date(); 
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss"); 
Date parsedDate = format.parse(YOUR_PICKED_DATE_AS_STRING); 
long alertTime = parsedDate.getTime() - now.getTime(); 

Intent someIntent = new Intent(getApplicationContext(), YourClass.class); 
PendingIntent pending = PendingIntent.getBroadcast(getApplicationContext(), 0, someIntent, 0); 

AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
manager.set(AlarmManager.