确切时间的Android通知

时间:2018-01-23 23:44:00

标签: android notifications alarmmanager alarm

对于我的生活,我无法弄清楚为什么我无法为Android通知设置确切的时间。一直试图弄清楚这几天,但仍然不明白为什么。

有时,它可以在时间选择器的同一时间运行。但是,有时它会延迟20秒,34秒甚至整整一分钟。如果有人可以帮助我,我会非常感激,因为我不知道还能做些什么。我从日期毫秒开始设置闹钟管理器的时间。

广播接收器:

public class AlertReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    int code = intent.getIntExtra("code", 0);

    Notification notification = new NotificationCompat.Builder(context)
            .setContentTitle("Task reminder!")
            .setTicker(intent.getStringExtra("taskText"))
            .setContentText(intent.getStringExtra("taskText"))
            .setSmallIcon(R.drawable.ic_stat_name)
            .setContentIntent(PendingIntent.getActivity(context, code, new Intent(context, MainActivity.class), 0))
            .setAutoCancel(true)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .build();
    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    notification.defaults = Notification.DEFAULT_SOUND;

    notificationManager.notify(code, notification);
}

}

MainActivity:

int code = new Random().nextInt(1200) + 

                    AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                    Intent intent = new Intent(getApplicationContext(), AlertReceiver.class);
                    intent.putExtra("taskText", taskInput.getText().toString());
                    intent.putExtra("code", code);
                    PendingIntent alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), code, intent, 0);

                    alarmMgr.set(AlarmManager.RTC, reminder, alarmIntent);

                    Intent i = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(i);

从中获取时间:

Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(System.currentTimeMillis());
            cal.set(Calendar.YEAR, datePicker.getYear());
            cal.set(Calendar.MONTH, datePicker.getMonth());
            cal.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
            cal.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
            cal.set(Calendar.MINUTE, timePicker.getCurrentMinute());
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);

1 个答案:

答案 0 :(得分:0)

修正了它!用setExact()替换了set()。

谢谢,迈克!