[英]Adding a reminder to the notification bar by date
I've been trying to figure out how I can have a user set a date for an item in my app, and then on the date that its set for, have it put a notification in the notification bar, even when they're not in the app. 我一直在试图弄清楚用户如何在应用程序中为项目设置日期,然后在设置日期的情况下,将其在通知栏中放置通知,即使他们没有在应用程序中。
Any help would be great. 任何帮助都会很棒。 Thanks 谢谢
You can use DatePicker to take Date from user. 您可以使用DatePicker从用户那里获取日期。 Use Alarm manager to set set alarm and then onReceive method build a notification. 使用“警报管理器”设置警报设置,然后使用onReceive方法构建通知。
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.addCategory("android.intent.category.DEFAULT");
PendingIntent broadcast = PendingIntent.getBroadcast(this, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, d); // Date for your notification
cal.add(Calendar.MONTH, m); // Date for your notification
cal.add(Calendar.YEAR, y); // Date for your notification
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), broadcast);
create a new java file AlarmReceiver.java in manifest add below code 在清单中创建一个新的Java文件AlarmReceiver.java ,添加以下代码
<receiver android:name=".AlarmReceiver">
<intent-filter>
<action android:name="android.media.action.DISPLAY_NOTIFICATION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
In AlarmReceiver.java
在AlarmReceiver.java
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
public class AlarmReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Intent notificationIntent = new Intent(context, NotificationActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(NotificationActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Notification notification = builder.setContentTitle("Demo App Notification")
.setContentText("New Notification From Demo App..")
.setTicker("New Message Alert!")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent).build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.