Android - 设置警报问题

时间:2012-07-31 07:51:45

标签: android calendar alarm

您好我正在通过推送创建闹钟,因此当我收到通知时,我会设置闹钟。一切正常,但是在我推动的那一刻,警报显示出来,而不是我说过的那一刻。

这是我的代码:

public void set_alarm(int year, int month, int day, int hour, int minute,
        String title) {

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MONTH, 5);
    cal.set(Calendar.YEAR, 2012);
    cal.set(Calendar.DAY_OF_MONTH, 31);
    cal.set(Calendar.HOUR_OF_DAY, 9);
    cal.set(Calendar.MINUTE, 46);

    Intent intent = new Intent(c, AlarmActivity.class);
    intent.putExtra("title", title);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
            c.getApplicationContext(), 1253, intent,
            PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);

    AlarmManager alarmManager = (AlarmManager) c
            .getSystemService(c.ALARM_SERVICE);

    alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
            pendingIntent);
}

以下是接收通知的类:

public class AlarmActivity extends BroadcastReceiver {

@Override
public void onReceive(Context c, Intent i) {
    Toast.makeText(c, "Alarm worked.", Toast.LENGTH_LONG).show();

    int icon = R.drawable.ic_dialog_alert;
    long when = System.currentTimeMillis();

    Bundle bundle = i.getExtras();
    String title = bundle.getString("title");

    final int NOTIF_ID = 1234;
    NotificationManager notofManager = (NotificationManager) c
            .getSystemService(Context.NOTIFICATION_SERVICE);

    Intent notificationIntent = new Intent(c, AnonymeActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(c, 0,
            notificationIntent, 0);
    Notification notification = new Notification(icon, "Faraway", when);

    notification.setLatestEventInfo(c, "Faraway alarm", title,
            contentIntent);

    notification.flags = Notification.FLAG_INSISTENT;
    notification.defaults |= Notification.DEFAULT_SOUND;

    notofManager.notify(NOTIF_ID, notification);
}

}

由于

1 个答案:

答案 0 :(得分:1)

您正在日期:05/31/2012创建一个日历实例,该日期位于当前日期之前。

根据文件:

  

如果过去发生时间,将立即触发警报。

只需设置正确的日期和时间即可。实际上,您应该使用传递给set_alarm()函数的参数。

(资料来源:http://developer.android.com/reference/android/app/AlarmManager.html#set(int, long, android.app.PendingIntent