Android倒计时器暂停和恢复不工作?

时间:2014-07-31 04:52:27

标签: android countdowntimer

我是Android新手并制作一个应用程序,其中有倒计时器,暂停和恢复切换按钮。当我暂停计时器暂停时,一切正常,但是当我恢复时它没有从暂停的地方恢复,它从实际的计时器在后台运行恢复。

我做了很多R& D但没有得到解决方案。请有人帮帮我。谢谢

这是我的代码:

  public class QuizActivityB extends Activity {  

   ToggleButton pauseTB;
   private String setQuestion, testName, time, timecounter;
   private String timeCounterFinish;
   private static double passedTime;
   private static Handler timeHandler = new Handler();
   private static double timeStart = SystemClock.uptimeMillis();;
   private TextView timeLabel;
   private static boolean initialStartTime = false;
   public double testTime;
   private double remaining;

   private Runnable updateTask = new Runnable() {

    public void run() {
        double duration = 60 * 1000 * testTime;
        double now = SystemClock.uptimeMillis();
        remaining = duration - passedTime - (now - timeStart);
        passedTime = now - timeStart + passedTime;
        timeStart = now;

        if (passedTime > 0) {
            int seconds2 = (int) (passedTime / 1000);
            int minutes2 = seconds2 / 60;
            seconds2 = seconds2 % 60;
            if (seconds2 < 10) {
                timeCounterFinish = "" + minutes2 + ":0" + seconds2;
            } else {
                timeCounterFinish = "" + minutes2 + ":" + seconds2;
            }

        }
        if (remaining > 0) {
            int seconds = (int) (remaining / 1000);
            int minutes = seconds / 60;
            seconds = seconds % 60;

            if (seconds < 10) {
                timeLabel.setText("Time Left: " + "" + minutes + ":0"
                        + seconds);
            } else {
                timeLabel.setText("Time Left: " + "" + minutes + ":"
                        + seconds);
            }

            timeHandler.postDelayed(this, 1000);
        } else {
            timeHandler.removeCallbacks(this);
            initialStartTime = false;
            passedTime = 0;
            timeStart = SystemClock.uptimeMillis();
            PostFinishedData();
            Intent intent = new Intent(QuizActivityB.this,
                    TestAnalysisActivity.class);
            intent.putExtra("userID", testID);
            intent.putExtra("time", time);
            intent.putExtra("currentDateandTime", date);
            intent.putExtra("score", finalScore);
            intent.putExtra("finalPercentage", finalPercentage);
            intent.putExtra("totalAttemp", setAttemptedQuestion);
            intent.putExtra("totalQuestions",
                    String.valueOf(totalQuestions));
            intent.putExtra("Wrong", WrongAnswers);
            intent.putExtra("Correct", correctQ);
            intent.putExtra("timecounter", timeCounterFinish);
            startActivity(intent);
            finish();

        }
    }
};

    pauseTB = (ToggleButton) findViewById(R.id.pauseBtIV);
    pauseTB.setBackgroundResource(R.drawable.pausebutton);
    finishBT.setVisibility(View.GONE);
    testName = getIntent().getStringExtra("testName");
    testTime = Integer.parseInt(getIntent().getStringExtra("time"));

   timeLabel = (TextView) findViewById(R.id.timeDetailsTV);
    timeLabel.setVisibility(View.VISIBLE);
    if (!initialStartTime) {
        timeStart = SystemClock.uptimeMillis();
        initialStartTime = true;
    }

    timeHandler.post(updateTask);

    pauseTB.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            if (isChecked) {
                pauseTB.setBackgroundResource(R.drawable.resumebutton);

           String timecounter = String.valueOf(passedTime);
                PausePrefEditor.putString("pauseTime", timecounter);
                PausePrefEditor.commit();

                timeHandler.removeCallbacks(updateTask);
                timeHandler = null;
                passedTime = 0;
                initialStartTime = false;
                timeStart = SystemClock.uptimeMillis();

            } else {
                // showToastResume();

                String time = pausePreference.getString("pauseTime", "");
                if (time.length() > 0) {
                    double timeSaved = Double.valueOf(time);
                    passedTime = timeSaved;
                    timeHandler = new Handler();
                    timeHandler.post(updateTask);
                }
    }

1 个答案:

答案 0 :(得分:1)

尝试使用此代码。它会对你有所帮助。

<强> Timer.java

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;

import android.database.Cursor;

import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Timer extends Activity {
Button b1,b2,b3;
      private TextView t1;

        private long startTime = 0L;

    private Handler customHandler = new Handler();

    long timeInMilliseconds = 0L;
        long timeSwapBuff = 0L;
    long updatedTime = 0L;

    SimpleDateFormat pp;

    String chec;
    String count;
    String name="Timer";
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.timer);
    t1=(TextView)findViewById(R.id.timerValue);
    b1=(Button)findViewById(R.id.startButton);
    b2=(Button)findViewById(R.id.pauseButton);
    b3=(Button)findViewById(R.id.button1);
    b1.setOnClickListener(new View.OnClickListener() {

                        public void onClick(View view) {
                            startTime = SystemClock.uptimeMillis();
                            customHandler.postDelayed(updateTimerThread, 0);

               }
                });



                b2.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View view) {

                        timeSwapBuff += timeInMilliseconds;
                        customHandler.removeCallbacks(updateTimerThread);

                    }
                });

    }
    public void reset(View v)
    {

     customHandler.removeCallbacks(updateTimerThread);
       // startTime = 0L;
        timeSwapBuff=0L;
        t1.setText("00:00:00");
    }
    private Runnable updateTimerThread = new Runnable() {

            public void run() {

                timeInMilliseconds = SystemClock.uptimeMillis() - startTime;

                updatedTime = timeSwapBuff + timeInMilliseconds;

                int secs = (int) (updatedTime / 1000);
                int mins = secs / 60;
                secs = secs % 60;
               int milliseconds = (int) (updatedTime % 1000);
                    t1.setText("" + mins + ":"
                            + String.format("%02d", secs) + ":"
                            + String.format("%03d", milliseconds));
                    customHandler.postDelayed(this, 0);
            }

            };
   }

<强> timer.xml

  <?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:background="#000000"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/timerValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/pauseButton"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="37dp"
        android:textSize="40sp"
        android:textColor="#ffffff"
        android:text="00:00:00" />

    <Button
        android:id="@+id/startButton"
        android:layout_width="90dp"
        android:layout_height="45dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="18dp"
        android:text="Start" />

    <Button
        android:id="@+id/pauseButton"
        android:layout_width="90dp"
        android:layout_height="45dp"
        android:layout_alignTop="@+id/startButton"
        android:layout_centerHorizontal="true"
        android:text="Pause" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/pauseButton"
        android:layout_marginLeft="15dp"
        android:layout_toRightOf="@+id/pauseButton"
        android:text="Reset" 
        android:onClick="reset"/>

</RelativeLayout>