如何在android中使用线程创建倒数计时器?

时间:2014-04-29 12:16:54

标签: android multithreading textview countdown

我有一个Android活动,显示2个日期之间的差异,但我想要的是显示计数停机时间的差异我尝试了这个代码,但它没有显示任何内容。

任何人都可以帮我解决这个问题???

firstActivity.java

package com.devleb.expandablelistdemo3;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class FirstActivity extends Activity {

    long diffSeconds;
    long diffMinutes;
    long diffHours;
    long diffDays;


    private Handler handler;
    private boolean Running = true;

    Date d1; 
    Date d2 = null;
    SimpleDateFormat format;

    String dateStop = "06/12/2014 23:00:00";

    // private DatabaseHelper dbHelper = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        getDiffDate();


    }

    public void listTeams(View v) {
        Intent in = new Intent(getBaseContext(), MainActivity.class);
        startActivity(in);
    }

    public void listGroups(View v) {
        Intent in = new Intent(getBaseContext(), GroupList.class);
        startActivity(in);
    }

    public void DisplaySched(View v) {

        Intent in = new Intent(getBaseContext(), MatchScheduleList.class);
        startActivity(in);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.first, menu);
        return true;
    }

    public void getDiffDate() {



        // HH converts hour in 24 hours format (0-23), day calculation
        format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

        d1 = new Date();

        d2 = null;

        handler = new Handler();




        Runnable runnable = new Runnable() {


            @Override
            public void run() {
                // TODO Auto-generated method stub
            while(Running){
                try{

                    d2 = format.parse(dateStop);

                    // in milliseconds
                    long diff = d2.getTime() - d1.getTime();

                     diffSeconds = diff / 1000 % 60;
                     diffMinutes = diff / (60 * 1000) % 60;
                     diffHours = diff / (60 * 60 * 1000) % 24;
                     diffDays = diff / (24 * 60 * 60 * 1000);

                    System.out.print(diffDays + " days, ");
                    System.out.print(diffHours + " hours, ");
                    System.out.print(diffMinutes + " minutes, ");
                    System.out.print(diffSeconds + " seconds.");


                    Thread.sleep(1000);//1 second
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        diffSeconds -= 1;

                        TextView txtDate = (TextView) findViewById(R.id.txtDifDate);
                        String resultDate = diffDays + "days " + diffHours + "Hours "
                                + diffMinutes + "Min " + diffSeconds + "S";
                        txtDate.setText(resultDate);
                    }
                });
            }
          }
        };



    }
}

1 个答案:

答案 0 :(得分:1)

有很多方法,需要注意的主要事项是如果你必须更新ui,你必须在ui线程上运行,如果我们使用CountDownTimer,这就是这样做

public class DateCountDownTimer extends CountDownTimer 
{

        public DateCountDownTimer(long startTime, long interval) 
        {
            super(startTime, interval);             
        }

        @Override
        public void onFinish() 
        {
            txvDate.setText("0 min 0 sec");
            this.cancel();
        }

        @Override
        public void onTick(long millisUntilFinished) 
        {
                 diffSeconds = millisUntilFinished / 1000 % 60;
                 diffMinutes = millisUntilFinished / (60 * 1000) % 60;
                 diffHours = millisUntilFinished / (60 * 60 * 1000) % 24;
                 diffDays = millisUntilFinished / (24 * 60 * 60 * 1000);
                 String resultDate = diffDays + "days " + diffHours + "Hours "
                            + diffMinutes + "Min " + diffSeconds + "S";
                 txtDate.setText(resultDate);
        }
    }

要启动计时器,请使用此

     long diff = d2.getTime() - d1.getTime();
     long interval=1000;
     DateCountDownTimer timer=new DateCountDownTimer(diff,interval);
     timer.start();//start the timer

还有其他各种方式AsyncTask

请接受答复,如果有帮助的话!

相关问题