我想在我的应用中每天在不同时间启动两项服务。为此,我在我的AlarmManager
和SplashActivity
中使用了SharedPreferences
我修正了这个AlarmManager
仅在第一次打开应用时运行。
我使用这些代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
//Check if first run, start alarms
SharedPreferences preferences = getSharedPreferences("init", MODE_PRIVATE);
if (preferences.getBoolean("firstTime", true)) {
startCheckService(getApplicationContext());
startMorningService(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstTime", false);
editor.apply();
}
这是警报的方法:
public void startCheckService(Context c){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,23);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
PendingIntent pi = PendingIntent.getService(c,0,new Intent(c,CheckService.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) c.getSystemService(ALARM_SERVICE);
am.cancel(pi);
am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),24 * 60 * 60 * 1000,pi);
}
public void startMorningService(Context c){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
PendingIntent pi = PendingIntent.getService(c,0,new Intent(c,CheckTodayEvents.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) c.getSystemService(ALARM_SERVICE);
am.cancel(pi);
am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),24 * 60 * 60 * 1000,pi);
}
但我的问题。每次我打开我的应用程序,alarmManager运行,我的服务运行。为什么?我怎么解决这个问题?
答案 0 :(得分:0)
最后我找到了解决方案。唯一要做的就是将PendingIntent的Service
和getService()
更改为BroadcastReceiver
:
public static void startCheckService(Context c){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,23);
calendar.set(Calendar.MINUTE, 45);
calendar.set(Calendar.SECOND, 0);
if(calendar.getTimeInMillis() >= Calendar.getInstance().getTimeInMillis()) {
PendingIntent pi = PendingIntent.getBroadcast(c, 0, new Intent(c, CheckService.class), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) c.getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTime().getTime(), AlarmManager.INTERVAL_DAY, pi);
}
}
我不知道为什么,但我的问题已经解决了。