当我的计时器到达随机时间时更改TextView

时间:2015-08-06 03:07:14

标签: java android

这是我到目前为止所拥有的

long startTime = 0;
TextView timerTextView;
final Handler timerHandler = new Handler();

Runnable timerRunnable = new Runnable() {
    @Override
    public void run() {
        long millis = System.currentTimeMillis() - startTime;
        int seconds = (int) millis / 1000;
        int minutes = (int) seconds / 60;
        seconds %= 60;

        int min = 40000;
        int max = 49999;
        long randomTime = (long) (Math.random()*(min-max) + max);

        timerTextView.setText(minutes + ":" + seconds);

        timerHandler.postDelayed(this, 500);
    }
};

我想知道如何使用randomTime变量来触发我的TextView更改为Time Is Up。我找到了一种使用以下方法创建计划任务的方法:

timerHandler.postAtTime(Runnable r, randomTime);

唯一的问题是我不知道Runnable应该使用TextView来改变require 'socket' local_socket = Socket.new(:INET, :STREAM) local_addr = Socket.pack_sockaddr_in(4481, '0.0.0.0') local_socket.bind(local_addr) local_socket.listen(Socket::SOMAXCONN) # accept a connection connection, remote_addr = local_socket.accept

1 个答案:

答案 0 :(得分:1)

首先将randomTime置于线程之外,

int min = 40000;
int max = 49999;
long randomTime = (long) (Math.random()*(min-max) + max);

创建一个简单的处理程序,该处理程序将在randomTime变量

指定的时间之后运行
new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {

                // handler has reached the time
                // now update the TextView using a runOnUiThread
                runOnUiThread(new Runnable() {
                public void run() {
                // Update UI elements

                // get the current time now
                long millis = System.currentTimeMillis() - startTime;
                int seconds = (int) millis / 1000;
                int minutes = (int) seconds / 60;
                seconds %= 60;

                //finally update the TextView
                timerTextView.setText(minutes + ":" + seconds);

                   }
                });

                }
            }, randomTime);