为了做这样的事情,你需要使用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类。