如何创建提醒通知

时间:2012-08-31 02:03:59

标签: android notifications android-notifications

我推荐了很多网站,但我仍然无法创建通知(提醒或闹钟) 我不确切知道如何创建和使用它。 它用于通知/提醒用户任务,并为用户提供每日提示.. 我很乐意帮助你这样做以及如何编码......

问候:) Thanxs提前为您提供帮助。

2 个答案:

答案 0 :(得分:39)

你需要两件事:

  • AlarmManager:定期(每天,每周,......)安排通知。
  • 服务:在AlarmManager关闭时启动通知。

这是一个基本的例子:

在您的活动中:

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);

这将在午夜(上午12点)每天触发警报 。如果你愿意,你可以改变它。

现在,创建一个服务NotifyService并将此代码放在onCreate()

@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);
}

此代码将在收到警报时显示通知。

祝你好运!

答案 1 :(得分:4)

这里有一点关于每日通知的YouTube Video Tutorial。您可以在说明中找到源代码。

此视频不是我自己制作的。但我认为这是一个快速的帮助。虽然我建议进行一些更改,因为Notification.Builder已弃用:

1

import android.support.v4.app.NotificationCompat;

2

// Change: Notification mNotify = new Notification.Builder(this) to
Notification mNotify = new NotificationCompat.Builder(this)

玩得开心!