Bạn cần hai điều:
- AlarmManager: lịch trình thông báo tại một căn cứ thường xuyên (hàng ngày, hàng tuần, ..).
- Dịch vụ: để khởi chạy thông báo khi AlarmManager tắt.
Dưới đây là một ví dụ cơ bản:
Trong hoạt động của bạn:
Intent myIntent = new Intent(this , NotifyService.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
calendar.add(Calendar.DAY_OF_MONTH, 1);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000*60*60*24 , pendingIntent);
này sẽ kích hoạt báo động mỗi ngày vào lúc nửa đêm (00:00). Bạn có thể thay đổi điều đó nếu bạn muốn.
Bây giờ, tạo ra một dịch vụ NotifyService
và đặt mã này trong onCreate()
của nó:
@Override
public void onCreate() {
NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.notification_icon, "Notify Alarm strart", System.currentTimeMillis());
Intent myIntent = new Intent(this , MyActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification.setLatestEventInfo(this, "Notify label", "Notify text", contentIntent);
mNM.notify(NOTIFICATION, notification);
}
Và đoạn mã này sẽ hiển thị các thông báo khi báo động được nhận.
Chúc may mắn!
bạn muốn có [Thông báo] (http://developer.android.com/guide/topics/ui/notifiers/notifications.html) hoặc [Báo thức] (http://developer.android.com/reference/ android/app/AlarmManager.html)? Hãy cụ thể – iTurki
[Câu trả lời] của tôi (http://stackoverflow.com/a/12189105/996493) có thể giúp bạn trong yêu cầu của bạn. – Lucifer
@iturki: Tôi muốn mã hóa cho cả hai .. – Rushabh