开发者

Implementing a simple loop in Android

So I come from the java world and normally when I want to loop I can just use something like开发者_如何转开发:

while(true) {
    //code here till false
}

but in Android I am noticing that that kind of loop, at least in my onCreate() method causes an application to not be runnable. My loop I want to use is really short and calls some simple UI updates (changes the background color).

How can I implement a loop in Android that calls UI changes? Where do I put this loop? (clearly not onCreate) Examples/sample code would be much appreciated.


On average, how many times does this loop execute? If it is a loop used to continually monitor something, you should probably use a new thread to do that. You could use a singleton and synchronize access to a few getters/setters to pass data back and forth.

You probably already know this, but if you use a while(true) loop, you should also have a Thread.sleep(...) in there so as not to lock down the CPU.

You could do something like this:

public class SingletonClass implements Runnable {

    private boolean someValue;

    public static final SingletonClass INSTANCE = new Test();

    private Test() {
      Thread t = new Thread(this);
      t.setDaemon(true);
      t.start();
    }

    public synchronized boolean getValue() {
      return someValue;
    }

    public synchronized void setValue(boolean value) {
      someValue = value;
    }

    @Override
    public void run() {
      while (true) {
        // ... do your work here...

        // Monitor something and set values
        setValue(true);

        Thread.sleep(500);
    }
  }
}

In your activity you could access the necessary items like this:

SingletonClass.INSTANCE.getValue()


You may want to rethink your design. You don't want to performing a blocking loop like that in the onCreate() method of your activity. You are preventing any UI updates and may end up just hanging your application. You will probably want to move the loop to an AsyncTask.


You also might try to look for an already existing method you can override/extend, like onDraw or onLayout. See the View documentation for further references.


I will recommend to use Handler and Runnable.

private Handler mHandler = new Handler();
private boolean isDone = false;
private Runnable indefinateTask = new Runnable() {
@Override
public void run() {
    if(isDone){
        mHandler.removeCallbacks(this);
    } else {
        //Perform Your Operation Over Here
        mHandler.postDelayed(indefinateTask, 1);
    }


}

};

and in onCreate call

new Thread(indefinateTask).start();

Might Help: http://developer.android.com/resources/articles/painless-threading.html

Hope this help. Cheers !!!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜