如何在Android应用中实现通知功能,在xml上设定的时间内,应用会显示通知?
假设本地xml文件的值为notifyat = 5:00pm,所以我希望每天都有应用程序,根据该值显示通知?
我一直在阅读本教程http://www.vogella.com/articles/AndroidNotifications/article.html
如何让应用程序每天自动读取xml文件并在指定时间显示通知?
答案 0 :(得分:0)
为了做这样的事情,你需要使用AlarmManager。以下是在此特定时间运行代码的示例:
// create intent
launchIntent = new Intent(this, MyAlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, launchIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
long interval = TimeUnit.DAYS.toMillis(1); // the interval is one day
long firstTime = 0;
// create a Calendar object to set the real time at which the alarm
// should go off
Calendar alarmTime = Calendar.getInstance();
alarmTime.set(Calendar.HOUR_OF_DAY, 17);
alarmTime.set(Calendar.MINUTE, 0);
alarmTime.set(Calendar.SECOND, 0);
Calendar now = Calendar.getInstance();
// set the alarm for today at 5pm if it is not yet 5pm
if (now.before(alarmTime)) {
firstTime = alarmTime.getTimeInMillis();
} else {
// set the alarm for the next day at 5pm if it is past 5pm
alarmTime.add(Calendar.DATE, 1);
firstTime = alarmTime.getTimeInMillis();
}
// Repeat every day at 5pm
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, firstTime, interval,
pendingIntent);
“MyAlarmReceiver”类是您放置启动通知的代码的地方。确保在AndroidManifest中声明您的BroadcastReceiver类。