AlarmManager ignores me and executes the event when he wants

0

I have a method that, with AlarmManager, on the 1st of each month should execute a code, but it executes it every time I open the application. It simply adds an entry to a database. I have this method:

public void crack(Context context){
        // Establecemos el calendario.
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        cal.set(Calendar.DAY_OF_MONTH, 1);

        AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Intent i = new Intent(context, ReceptorCrack.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, i, 0);

        manager.set(AlarmManager.RTC, cal.getTimeInMillis(), pendingIntent);
    }
    
asked by PacoPepe 24.05.2018 в 16:28
source

2 answers

2

One way would be to get the first day of the next month:

// obtienes la fecha actual (hoy es 25/05/2018)
Calendar cal = Calendar.getInstance();
int actualAnio = cal.get(Calendar.YEAR);  // 2018
int actualMes = cal.get(Calendar.MONTH);  // 05
// este es el día 1 del mes:
int primerDia = cal.getActualMinimum(Calendar.DAY_OF_MONTH);  

//así seteas esa fecha, en este caso queda 01/05/2018 08:30 am
cal.set(actualAño, actualMes, primerDia, 8,30,0);
// le agregas un mes 
cal.add(Calendar.MONTH,1);
// por lo que quedaría así: 01/06/2018
// cal.add(Calendar.DAY_OF_MONTH, 4);  // si quieres que sea el día 5 ...
//lo puedes corroborar en el logCat:
Log.i("FECHA ", String.valueOf(cal.getTime()));

By the time you are in June, you must change to 01/07/2018 and so on every month.

    
answered by 26.05.2018 / 00:50
source
0

You're using AlarmManager.RTC

  

AlarmManager.RTC : This alarm does not activate the device; if it goes off while the   device is asleep, it will not be sent until the next time the   device wakes up.

Therefore, RTC will deliver intent only when the device is activated.

You must use AlarmManager.RTC_WAKEUP  if you want your service to perform some operation since AlarmManager.RTC_WAKEUP will activate the device and deliver the pending attempt.

    
answered by 24.05.2018 в 17:07