0

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?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Sadeq Shajary
  • 427
  • 6
  • 17

1 Answers1

0

Finally I found solution. Only thing to do is change Service And getService() of PendingIntent to 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);
    }
}

I don't know why but my problem is resolved.

Sadeq Shajary
  • 427
  • 6
  • 17