我真的厌倦了我创建的警报服务。我创建了一个警报服务,用于在我的应用程序中每天早上 8 点、下午 4 点、上午 12 点在我的应用程序中显示警报。它工作正常并且警报显示完美。我在关闭应用程序时取消了我的服务,但有时警报没有达到时间,例如退出应用程序后,从标签历史记录中删除应用程序时,当进行设备设置时,我不明白为什么发生这种情况,我正在检查 SO 中的解决方案,但没有得到任何适当的解决方案,请在这里帮助我提供我的代码。
public void StartService()
{
Calendar c = Calendar.getInstance();
dfcurrent = new SimpleDateFormat("dd MMM yyyy");
long currentTime = System.currentTimeMillis();
currentdate = new Date(System.currentTimeMillis());
String currentdate1 = dfcurrent.format(currentdate);
Long datetoalert1 = Utility.DateReturn(currentdate1+" - "+08:00AM);
if(datetoalert1 < currentTime)
{
Date d = new Date(datetoalert1);
c.setTime(d);
c.add(Calendar.DATE, 1);
d = c.getTime();
datetoalert1 = d.getTime();
}
Long datetoalert2 = Utility.DateReturn(currentdate1+" - "+04:00PM);
if(datetoalert2 < currentTime)
{
Date d = new Date(datetoalert2);
c.setTime(d);
c.add(Calendar.DATE, 1);
d = c.getTime();
datetoalert2 = d.getTime();
}
Long datetoalert3 = Utility.DateReturn(currentdate1+" - "+00:00AM);
if(datetoalert3 < currentTime)
{
Date d = new Date(datetoalert3);
c.setTime(d);
c.add(Calendar.DATE, 1);
d = c.getTime();
datetoalert3 = d.getTime();
}
Intent myIntent1 = new Intent(Login.this, MyReceiver.class);
pendingIntentSApp1 = PendingIntent.getBroadcast(Login.this, 7, myIntent1,0);
pendingIntentSApp2 = PendingIntent.getBroadcast(Login.this, 8, myIntent1,0);
pendingIntentSApp3 = PendingIntent.getBroadcast(Login.this, 9, myIntent1,0);
AlarmManager alarmManager1 = (AlarmManager)getSystemService(ALARM_SERVICE);
AlarmManager alarmManager2 = (AlarmManager)getSystemService(ALARM_SERVICE);
AlarmManager alarmManager3 = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager1.set(AlarmManager.RTC, datetoalert1, pendingIntentSApp1);
alarmManager2.set(AlarmManager.RTC, datetoalert2, pendingIntentSApp2);
alarmManager3.set(AlarmManager.RTC, datetoalert3, pendingIntentSApp3);
}
我在关闭应用程序时取消了这个挂起的意图。这里给出代码
public void exit_btn_click(View view)
{
Intent myIntent1 = new Intent(Login.this, MyReceiver.class);
pendingIntentSApp1 = PendingIntent.getBroadcast(Login.this, 7, myIntent1,0);
pendingIntentSApp2 = PendingIntent.getBroadcast(Login.this, 8, myIntent1,0);
pendingIntentSApp3 = PendingIntent.getBroadcast(Login.this, 9, myIntent1,0);
AlarmManager alarmManager1 = (AlarmManager)getSystemService(ALARM_SERVICE);
AlarmManager alarmManager2 = (AlarmManager)getSystemService(ALARM_SERVICE);
AlarmManager alarmManager3 = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager1.cancel(pendingIntentSApp1);
alarmManager2.cancel(pendingIntentSApp2);
alarmManager3.cancel(pendingIntentSApp3);
System.exit(0);
}