1

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();
4

1 回答 1

1

您必须通过 setter 方法设置变量。然后,您可以对这种变化做出反应。

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

一个更优雅的方法是观察者模式,在这里你可以找到关于它的更详细的文档。

你当然必须避免while(true)在移动设备上出现循环,它会耗尽你的电池并且你也会阻塞 UI 线程。这就是为什么您的 UI 没有响应并且您的手机很烫的原因。

于 2013-06-12T13:07:43.360 回答