2

我有这段代码,我可以在其中一次从日期选择器和时间选择器中设置时间和日期:

 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,现在我想向该选定时间的用户发出警报(作为警报)。我为此使用了警报管理器,但它不允许我选择那个日期?

我怎样才能做到这一点?

4

1 回答 1

2

如果您查看 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

所以基本上你应该做的是获取所选日期(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.
于 2012-09-18T15:54:32.063 回答