How do I make an action at a specific time when the phone is blocked?

0

I have this method. The problem is that it does not work when I lock the phone. Only shows me the notification if the phone has the screen on, if I block it and I put it to activate only 5 minutes later (it's 9:00 p.m. and I set it to 9:05 p.m.), nothing happens. But I leave it with the screen on if you show me the notification. Thanks in advance

public void activarBroucast(int a,int b) {
      int minutos=a;
      int horas=b;
       Calendar c = Calendar.getInstance();
       c.add(Calendar.HOUR,horas);
       c.add(Calendar.MINUTE,minutos);
       Timer time = new Timer();
       time.schedule(new TimerTask() {
           @Override
           public void run() {
              lanzarNotificacion();
           }
       },c.getTime());
   }
    
asked by Andry_UCI 26.03.2018 в 13:24
source

1 answer

2

It is a mistake to suppose that the application will remain active for X time after going to the background or if the phone is blocked. In particular in these cases the app is paused and even the OS can decide to destroy it.

Option 1

If it is very important to show the notification after an exact time, it is convenient to use Alarms , since they run outside of the application's life cycle. This is important because as I said above, the problem you are having comes from the app pausing after the screen lock.

Option 2

Instead of showing the notification after a certain time, what can be done is:

  • Show the notification when the device is unlocked if it has already passed N milliseconds
  • Reconfigure a task to execute after N-DURACION_DE_LOCK milliseconds

This produces the same effect that was sought. One way to react to the unlock event is to create a broadcast that listens to ACTION_USER_PRESENT

Option 3

Another possible solution (although not recommended) is to use a partial wake lock so that the app continues its execution even after blocking the screen.

Depending on the intention of what you are wanting to do, I would recommend reading a bit about how to declare Jobs on android at official documentation

    
answered by 26.03.2018 в 22:46