I want to Start two services at different times in daily period in my app. for this purpose I use AlarmManager
in my SplashActivity
and with SharedPreferences
I fix that this AlarmManager
run just for the first time that app opening.
I uses this codes:
@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();
}
and this is alarm's method:
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);
}
but my problem. every time I open my app, alarmManager run and my services do run. why? how can I solve this?