【问题标题】:Best way to perform an action periodically [while an app is running] - Handler?[在应用程序运行时]定期执行操作的最佳方式 - 处理程序?
【发布时间】:2011-03-27 20:56:53
【问题描述】:

我正在尝试定期执行一项操作。我想在每 3 秒后创建一个类的新实例。最好通过使用处理程序或线程来实现这一点?我可以尝试一种更简单、更愚蠢的方法吗?我真的不擅长使用线程——我想学习,但更重要的是在担心良好的编程实践之前让它发挥作用。

    new Thread(){
        public void run(){
            //makes sure the player still has 3 lives left
            while(game == false){
                uiCallback.sendEmptyMessage(0);
                try {
                    Thread.sleep(2000); // wait two seconds before drawing the next flower
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } //sleep for 2 seconds
            }
        }
    }.start();

【问题讨论】:

    标签: android multithreading handler


    【解决方案1】:

    我在我的 android 应用中做类似的事情;我每 10 秒更新一次界面中的一些数据。有很多方法可以做到这一点,但我选择使用Handler,因为它实现起来非常简单:

    Thread timer = new Thread() {
        public void run () {
            for (;;) {
                // do stuff in a separate thread
                uiCallback.sendEmptyMessage(0);
                Thread.sleep(3000);    // sleep for 3 seconds
            }
        }
    });
    timer.start();
    ...
    private Handler uiCallback = new Handler () {
        public void handleMessage (Message msg) {
            // do stuff with UI
        }
    };
    

    您可能知道,您不能在 UI 线程中运行这样的周期性函数,因为它会阻塞 UI。这会创建一个新的Thread,它会在完成后向 UI 发送一条消息,因此您可以使用周期性函数执行的任何新结果来更新您的 UI。

    如果您不需要使用此周期函数的结果更新 UI,您可以简单地忽略我的代码示例的后半部分,并生成一个新的 Thread,如图所示。但是请注意:如果您正在修改这个新的Thread 和 UI 共享的变量,如果您不同步,您将会遇到问题。一般来说,线程不是一个你想忽略“良好编程实践”的领域,因为你会遇到奇怪的、不可预测的错误,而且你会诅咒你的程序。

    -tjw

    【讨论】:

    • 嗯,总有一天我得坐下来试着解决它。我正在做的是实现从屏幕顶部落下的无限数量的图像,但我不希望它们一次全部落下,我希望每 5 秒一次。这一切都是在 SurfaceView 中执行的,所以希望我仍然可以使用这个 Handler。
    • 是的,那么我的方法正是你想要的。顶部代码块将是您的“计时器”,底部代码块将执行使单个图像从屏幕顶部落下的代码。
    • for 循环的参数是什么?
    • for(;;) 表示循环永远运行。它相当于while(true)。如果您希望它在某个时候停止,您需要添加自己的条件。
    • 好的,知道了。所以从技术上讲,如果我希望它只在游戏状态为真时运行(比如当这个人还剩 3 条生命时,或者我打算这样做),我可以用一段时间替换那个 for 语句?而(游戏 == 真)?
    【解决方案2】:

    最简单的方法是在View(例如,小部件)上使用postDelayed() 来安排一个有效的Runnable,然后重新安排自己。

    【讨论】:

    【解决方案3】:
    // We need to use this Handler package
    import android.os.Handler;
    
    // Create the Handler object (on the main thread by default)
    
    Handler handler = new Handler();
    
    // Define the code block to be executed
    
    private Runnable runnableCode = new Runnable() {
        @Override
        public void run() {
          // Do something here on the main thread
          Log.d("Handlers", "Called on main thread");
          // Repeat this the same runnable code block again another 2 secs
          // 'this' is referencing the Runnable object
          handler.postDelayed(this, 2000);
        }
    };
    // Start the initial runnable task by posting through the handler
    handler.post(runnableCode);
    

    【讨论】:

      猜你喜欢
      • 2014-04-13
      • 1970-01-01
      • 1970-01-01
      • 2011-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多