我在android中制作一个警报应用程序,它将在每天晚上8点触发警报。我正在使用此代码触发警报
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 20);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
Intent intentservice = new Intent(MainActivity.this, MyAlarmService.class);
//create a pending intent to be called at 6 AM
PendingIntent Pintent = PendingIntent.getService(MainActivity.this, 0, intentservice, PendingIntent.FLAG_UPDATE_CURRENT);
//schedule time for pending intent, and set the interval to day so that this event will repeat at the selected time every day
AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(ALARM_SERVICE);
//schedule time for pending intent, and set the interval to day so that this event will repeat at the selected time every day
am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 24*3600*1000, Pintent);
,服务类是
public class MyAlarmService extends Service
{
private NotificationManager mManager;
@Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),SecondActivity.class);
Calendar c = Calendar.getInstance();
Log.w("**********************","enter ***************** ");
// Log.w("enter dateeeeeeee"," "+c.get(Calendar.DAY_OF_MONTH));
int thisDay = c.get(Calendar.DAY_OF_MONTH);
intent1.putExtra("dateeee", thisDay);
Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);
mManager.cancel(0);
mManager.notify(0, notification);
}
@Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
现在的问题是我每天都会收到两次相同的通知。我想在一天内发出一次通知,但它不是这样做的。警报在错误的时间间隔内重复。任何人都可以帮忙我
答案 0 :(得分:0)
有一个常数。 http://developer.android.com/reference/android/app/AlarmManager.html
替换
am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 24*3600*1000, Pintent);
与
am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), am.INTERVAL_DAY, Pintent);