简体   繁体   中英

I would like to show the timer of a thread in textView (Live)

I have a timer in a thread waiting like 20 seconds before moving to a new activity, what I'm looking for is to show the time whatever decreasing or increasing in a textView in that while. here's my code:

Thread timer = new Thread() {
        public void run() {
            try {
                sleep(ie);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {

                Intent i = new Intent(Activity.this, Menu.class);
                if (ie == 20000) {
                    startActivity(i);
                    overridePendingTransition(R.anim.pushin, R.anim.pushout);
                }
            }
        }
    };

    timer.start();

thanks for your assisstance

Try a CountDownTimer instead of a Thread:

            CountDownTimer count = new CountDownTimer(20000, 1000)
            {

                int counter = 20;

                @Override
                public void onTick(long millisUntilFinished)
                {
                    // TODO Auto-generated method stub
                    counter--;
                    textView.setText(String.valueOf(counter));

                }

                @Override
                public void onFinish()
                {

            startActivity(i);
            overridePendingTransition(R.anim.pushin, R.anim.pushout);
                }
            };

            count.start();

Camilo Sacanamboy's answer is the correct one. If you want to do this with a Thread, one solution might be like this:

final TextView status; //Get your textView here

    Thread timer = new Thread() {
        public void run() {
            int time = 20000;
            try {
                while(time > 0){
                    time -= 200; //Or whatever you might like

                    final int currentTime = time;
                    getActivity().runOnUiThread(new Runnable() { //Don't update Views on the Main Thread
                        @Override
                        public void run() {
                            status.setText("Time remaining: " + currentTime / 1000 + " seconds");
                        }
                    });
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {

                Intent i = new Intent(Activity.this, Menu.class);
                if (ie == 20000) {
                    startActivity(i);
                    overridePendingTransition(R.anim.pushin, R.anim.pushout);
                }
            }
        }
    };

    timer.start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM