0

I would like to ask a general post Delay question. So I'm using this method in my app, but it seems it is not working as I have expected.

What I'm trying to check is say :

private boolean privateVariable = false    // private instance field
new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if(privateVariable)) {       
                //DO SOMETHING
            }
        }
    }, 5000);

and privateVariable got updated as true within the 5 seconds of delay. Does DO SOMETHING gets executed??

In other words, when we use postdelay method, are we saving the variables when we delay it and use it after certain amount of delay, or are we using the updated variable when the run() gets executed after 5 seconds? It seems in my app it saves it, so even though I change it in between the 5 second delay, it uses the original one that it was when I made the new handler.

If it uses the saved one, can you please inform me of a way to use the updated value after certain amount of time?

Thank you in advance.

petey
  • 16,914
  • 6
  • 65
  • 97
joony0123
  • 41
  • 8
  • `Does DO SOMETHING gets executed??` and what does `Log.d` say? – pskink Mar 28 '17 at 16:36
  • 1
    it depends which thread is updating the variable and which thread is handler attached to. If your handler is created on main thread and you are updating the variable from some background thread,then you will need synchronization like declaring variable as volatile. – Jagroshan Mar 28 '17 at 17:04
  • @Jagroshan Thanks for the comment. So this is how my app goes. When it starts it starts a service that runs in background in START_STICKY with startForeground() because I want to run this in background and at the same time not get killed easily. In that service I have this Activity that has the private variable and it gets updated within the same activity. The handler is also in the same activity. Any further suggestion? – joony0123 Mar 28 '17 at 17:14
  • @pskink Thanks for the comment. Apparently it seems it uses the saved value. – joony0123 Mar 28 '17 at 17:15

0 Answers0