开发者

Handler/Runnable not working with loop

I am trying to get my TextView to update in a separate thread so that it doesn't slow down my UI. It works, but when I add in a while loop to control it, it hangs the program in a black screen.

Code:

handler.post(new Runnable(){
           @Override
            public void开发者_StackOverflow run() {

            while(media[6].isPlaying()) {

            TextView myText = (TextView)findViewById(R.id.timerT);   

            myText.setText(getTimeString(media[1].getCurrentPosition()));        


            handler.postDelayed(this,10);
                                        }
        }

    });

I thought that the runnable creates a new thread, meaning that this wouldn't happen? Or am I going badly wrong?


Use CountDownTimer class like below:

// Function arguments are in milliseconds. 
CountDownTimer timer = new CountDownTimer(6000, 1000) {

    public void onTick(long millisUntilFinished) {
        //mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);

        // Do your stuff here.

        TextView myText = (TextView)findViewById(R.id.timerT);

        myText.setText(getTimeString(media[1].getCurrentPosition()));
    }

    public void onFinish() {
        mTextField.setText("done!");
    }
}

timer.start();


Your black screen is because you are running an arbitrary duration while loop on the event dispatch thread: never do this. For something of this sort you want to use AsyncTask or start your Runnable in a separate thread and then use View.post to send the timer updates only.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜