android - 如何创建提醒通知

标签 android notifications android-notifications

我已经推荐了很多网站,但我仍然无法创建通知(提醒或警报) 我不知道如何创建和使用它。 它通知/提醒用户有关任务,并为用户提供每日提示.. 我很高兴得到您的帮助以及如何编写代码......

问候:) 提前感谢您的帮助。

最佳答案

你需要两件事:

  • AlarmManager:定期(每天、每周……)安排您的通知。
  • 服务:在 AlarmManager 关闭时启动通知。

这是一个基本的例子:

在您的 Activity 中:

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

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

祝你好运!

关于android - 如何创建提醒通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12208008/

相关文章:

javascript - 使用小书签中的通知 API

android - startForeground的 channel 无效

android - 大通知图标旁边的灰色圆圈?

php - 如何使用 FCM 使用 php 脚本向多个设备发送推送通知?

android - 仅当 Activity 在后台时才将其带到前台的通知

android - 辅助功能服务消耗大量电池

ios - 在 WatchOS 端创建自定义 Long-Nook 通知

c# - 如何创建最小化的持续通知,如 USB 连接或谷歌天气

android - 将 AChartEngine 库用于图形,无法获取不同 x 轴值的值

android - 访问设备根目录下的文件