我正在使用代码根据特定条件每小时向用户显示一条通知。我正在学习,所以最基本的代码就在这里。
Log.v("Service Started", "onStartCommand");
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
Log.v("Show Notification", "Showing notification at "+System.currentTimeMillis());
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
long[] pattern = {500,500,500,500,500,500,500,500,500};
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent intent1 = new Intent(getBaseContext(), SplashScreen.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(),123,intent1,0);
Notification notification = new NotificationCompat.Builder(getBaseContext())
.setContentTitle("Dimensions Weather & News")
.setContentText("Thank you for using our app.")
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setLights(Color.BLUE, 500, 500)
.setVibrate(pattern)
.setSound(alarmSound)
.setSmallIcon(R.drawable.ic_launcher).getNotification();
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(123, notification);
}
}, 0, 3600000);
但它不时地显示通知,而不是一小时的间隔。大部分时间它在前一个时间后6-7分钟显示。为什么呢?
答案 0 :(得分:0)
TimerTask依赖于系统的时间,使用AlarmManager instand它。