我希望退出处理程序并在完成其工作后返回活动代码

时间:2016-10-02 18:09:27

标签: android timer handler runnable countdown

我一直试图弄清楚如何使用' handler()'来制作倒数计时器。我仍然不知道如何制作它,以便应用程序执行该行" Finished"当倒计时达到0时。

我想要输入“UpdateGUI()'”中的任何代码行。退出runnable并返回主活动以显示"已完成"。

我的编码时间不长,所以也许这是一个明显的答案,但我无法在本页的任何主题上找到它......

非常感谢一些帮助: - )

谢谢

public class MainActivity extends AppCompatActivity {

    int i = 10;
    TextView tv;
    final Handler myHandler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button but = (Button) findViewById(R.id.button);

        but.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                tv = (TextView) findViewById(R.id.textView);

                Timer myTimer = new Timer();
                myTimer.schedule(new TimerTask() {
                   @Override
                    public void run() {
                        UpdateGUI();
                    }
                }, 0, 1000);
                tv = (TextView) findViewById(R.id.textView);
                tv.setText("Finished");
            }
        });
    }

    private void UpdateGUI() {
        if (i == 0) {
            //this is where i need to enter the code!!
        }
        else
            i--;
        myHandler.post(myRunnable);
    }

    final Runnable myRunnable = new Runnable() {
        public void run() {
           tv.setText(String.valueOf(i));
        }
    };
}

1 个答案:

答案 0 :(得分:0)

如果我在一段时间后需要运行你的runnable,我会正确理解你使用Handler方法 postDelayed(runnable,timeOutInMillis)

更新:处理程序计时器的示例

int timesRun;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
    public void run() {
        runTimer();
        i++;
    }
};  

// call it in button callback
  public void runTimer(){
      // update your timer here
      if (i != 10) // if 10 seconds not passed run it one more time
      handler.postDelayed(runnable, 1000); // run every second
  }

请注意,这不是最优雅的方法,但仍然可以使用