在Android中实现一个简单的循环 [英] Implementing a simple loop in Android

查看:107
本文介绍了在Android中实现一个简单的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我来自Java世界,通常当我想循环时,我可以使用类似这样的东西:

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
}

,但是在Android中,我注意到这种循环,至少在我的onCreate()方法中,这种循环导致应用程序无法运行.我要使用的循环确实很短,并调用了一些简单的UI更新(更改了背景颜色).

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).

如何在Android中实现调用UI更改的循环?我在哪里放置此循环? (显然不是onCreate)示例/示例代码将不胜感激.

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.

推荐答案

此循环平均执行多少次?如果这是一个用于连续监视某些事物的循环,则可能应该使用新线程来执行此操作.您可以使用单例并同步对一些getter/setter的访问以来回传递数据.

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.

您可能已经知道这一点,但是如果使用while(true)循环,则还应该在其中有一个Thread.sleep(...),以免锁定CPU.

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.

您可以执行以下操作:

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

这篇关于在Android中实现一个简单的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆