Eric Glass
Eric Glass

Reputation: 141

Android - Proper way to listen for variable change, and do something upon change?

The app I'm making requires that a bit of code be executed whenever the value of a particular variable changes from 0 to 1.
The handler example below is the method I'm currently using to do this (I copied it from someone else).
I have a feeling it's not a proper method though because having just three of these handlers in my app causes the UI to be fairly unresponsive, and causes the device (a phone) to become quite hot.
As you can see, I've put 10ms delays in the handlers to try to deal with this.
Isn't there something more like OnClickListener that can listen at all times for a variable value change without putting such stress on the CPU?
I'm pretty new to Java and Android so a simple example would be very much appreciated.

  final Handler myHandler1 = new Handler();
  new Thread(new Runnable()
  {
  @Override
     public void run()
     {
        while (true)
        {
           try
           {
           Thread.sleep(10);
           myHandler1.post(new Runnable()
              {
              @Override
                 public void run() 
                 {
                    if (myVariable == 1)
                    {
                    myVariable = 0;
                    //do stuff
                    }   
                 }
              });
           } catch (Exception e) {}
        }
     }  
  }).start();

Upvotes: 1

Views: 1680

Answers (1)

ejoncas
ejoncas

Reputation: 329

You must set your variable via a setter method. Then, you can be reactive to that change.

public void setMyVariable(int value) {
this.myVariable = value;
if (myVariable == 1) {
  doSomethingWhen1();
} else if (myVariable == 0) {
  doSomethingWhen0();
}
}

A more elegant way to do that will be an observer pattern, Here you can find more detailed documentation about it.

You must certainly avoid while(true) loops on mobile device, it will drain your battery and you are also blocking the UI thread. That's the reason why your UI is unresponsive and your cellphone it's quite hot.

Upvotes: 1

Related Questions