Timer Task不会在android中每秒更新一次值

时间:2015-02-04 17:41:25

标签: android timertask

  

我已经使用计时器任务每秒运行一次。

     

使用diffSeconds = diff /(1000);每1秒更新一次,但仅在60秒后执行。

     

我需要每秒更新一次计时器,并用秒值更新ui。

mTimerTask = new TimerTask() {
                    public void run() {
                            handler.post(new Runnable() {
                                    public void run() { 
                                        /*int n = 0;
                                        if (n ==0){*/
                                        String endTime = DataHandler.getInstance().getEndTime();
                                        Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+5:30"));
                                        Date currentLocalTime = cal.getTime();
                                        DateFormat df = new SimpleDateFormat("HH:mm");
                                        df.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
                                        String localTime = df.format(currentLocalTime); 
                                        Date currentTime = null;
                                        Date dateEndTime = null;
                                        long diff, diffMinutes, diffSeconds;
                                        try {
                                            dateEndTime = df.parse(endTime);
                                            currentTime = df.parse(localTime);
                                            diff = dateEndTime.getTime() - currentTime.getTime();
                                            diffMinutes = diff / (60 * 1000);
                                            diffSeconds = diff / (1000);
                                            System.out.println("Time in minutes: " + diffMinutes + " minutes.");  
                                            difference = Long.toString(diffMinutes);
                                            differenceseconds = Long.toString(diffSeconds);

                                            timenumber.setText(differenceseconds);
                                            if(diffSeconds==1){
                                                startAlarm();
                                                //String endTime = DataHandler.getInstance().getEndTime();

                                            }
                                            SupremeLogger.d("localtime", localTime);
                                            SupremeLogger.d("endtime", endTime);
                                            SupremeLogger.d("difference in minutes", difference);
                                            SupremeLogger.d("Difference in seconds", differenceseconds);
                                        } catch (ParseException e1) {
                                            // TODO Auto-generated catch block
                                            e1.printStackTrace();
                                        }





                                        }


                           });
                    }};


                t.schedule(mTimerTask, 0, 1000);

            }

1 个答案:

答案 0 :(得分:2)

我使用AsyncTask做到了这一点。这是我的代码。这将更新你每秒传递给它的构造函数的TextView,显示它像(分钟):(秒)。

private class TimerUpdateTask extends AsyncTask<Void, Void, Void>{
    private static final String TAG = "TimerUpdateTask";
    private long startTime;
    boolean running = true;

    TextView tvTime;

    public void kill(){
        running = false;
    }

    public TimerUpdateTask(TextView tvTime){
        this.tvTime = tvTime;
    }

    public void onPreExecute(){
        this.startTime = System.currentTimeMillis();
    }

    @Override
    public void onProgressUpdate(Void... p){
        long current = System.currentTimeMillis();
        long elapsed = current - startTime;
        String time = "" + elapsed / 60 + ":"; // does minutes : seconds
        if (s % 60 < 10) { 
            time += "0" + (s % 60);
        } else {
            time += (s % 60);
        }
        tvTime.setText(time);
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        long last = startTime;
        while (running){
            while (last / 1000 + startTime % 1000 == 
                    System.currentTimeMillis() / 1000 + startTime % 1000){
                try {  // busy waiting with 50 ms rests.
                    Thread.sleep(50);
                } catch (Exception e){}
                if (!running) break;
            }
            last = System.currentTimeMillis();
            publishProgress();
        }
        return null;
    }

    @Override
    public void onPostExecute(Void result){
        if (running){
            Log.wtf(LAG, "wtf");
        } else {
            Log.d(TAG, "killed");
        }
    }
}

实例化此TimerUpdateTask并将其保存为本地变量,然后,当您想要停止时,请调用其someTimerUpdateTask.kill()