Как реализовать паузу и возобновить обратный отсчет?

Я реализовал таймер обратного отсчета в своем приложении. Он работает нормально. Теперь я реализовал кнопку выхода в своем приложении с разрешением диалогового окна (да или нет). Когда пользователь нажимает «да», затем выходит и не возвращается в игру. Теперь моя проблема в том, как приостановить таймер обратного отсчета, когда я нажимаю кнопку выхода, и возобновить без кнопки в диалоговом окне.

Вот мой код:-

public class QuestionActivity extends Activity implements OnClickListener{
    private Question currentQ;
    private GamePlay currentGame;
    public CountDownTimer counterTimer;
    private Button nextBtn1, nextBtn2, nextBtn3, nextBtn4, nextBtn5;


            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.question);
                processScreen();
         }
                /**
         * Configure current game and get question
         */
         private void processScreen()
         {
        currentGame = ((Application)getApplication()).getCurrentGame();
        currentQ = currentGame.getNextQuestion();
        nextBtn1 = (Button) findViewById(R.id.answer1);
        nextBtn1.setEnabled(true);
        nextBtn1.setOnClickListener(this);
        nextBtn2 = (Button) findViewById(R.id.answer2);
        nextBtn2.setEnabled(true);
        nextBtn2.setOnClickListener(this);
        nextBtn3 = (Button) findViewById(R.id.answer3);
        nextBtn3.setEnabled(true);
        nextBtn3.setOnClickListener(this);
        nextBtn4 = (Button) findViewById(R.id.answer4);
        nextBtn4.setEnabled(true);
        nextBtn4.setOnClickListener(this);
        nextBtn5 = (Button) findViewById(R.id.answer5);
        nextBtn5.setEnabled(true);
        nextBtn5.setOnClickListener(this);
        /**
         * Update the question and answer options..
         */
        setQuestions();

    }

     /**
     * Method to set the text for the question and answers from the current games
     * current question
     */
    private void setQuestions() {
        //set the question text from current question
        String question = Utility.capitalise(currentQ.getQuestion());
        TextView qText = (TextView) findViewById(R.id.question);
        qText.setText(question);
         //set the available options
        List<String> answers = currentQ.getQuestionOptions();
        TextView option1 = (TextView) findViewById(R.id.answer1);
        option1.setText(Utility.capitalise(answers.get(0)));
        TextView option2 = (TextView) findViewById(R.id.answer2);
        option2.setText(Utility.capitalise(answers.get(1)));
        TextView option3 = (TextView) findViewById(R.id.answer3);
        option3.setText(Utility.capitalise(answers.get(2)));
        TextView option4 = (TextView) findViewById(R.id.answer4);
        option4.setText(Utility.capitalise(answers.get(3)));
        int score = currentGame.getScore();
        String scr = String.valueOf(score);
        TextView score1 = (TextView) findViewById(R.id.score);
        score1.setText(scr);

        counterTimer = new CountDownTimer(15000, 1000) {
        public void onFinish() {                
                if(currentGame.getRound()==20)
                {
                nextBtn1.setEnabled(false);
                nextBtn2.setEnabled(false);
                nextBtn3.setEnabled(false);
                nextBtn4.setEnabled(false);
                nextBtn5.setEnabled(false);
                final Handler handle = new Handler();
                Toast.makeText(QuestionActivity.this, "Time's Up", Toast.LENGTH_SHORT).show();
                Runnable delay = new Runnable() {
                    public void run() {
                        System.exit(0);
                    }
                };
                handle.postDelayed(delay,3000);
                }

                else if(currentGame.getRound()==0)
                {
                currentGame.decrementScore();
                final Handler handle = new Handler();
                Runnable delay = new Runnable() {
                    public void run() {
                        processScreen();
                    }
                };
                handle.postDelayed(delay,3000);
                }

                else if(currentGame.getRound()==19)
                {
                        nextBtn1.setEnabled(false);
                        nextBtn2.setEnabled(false);
                        nextBtn3.setEnabled(false);
                        nextBtn4.setEnabled(false);
                        nextBtn5.setEnabled(false);
                        currentGame.decrementScore();
                        final Handler handle = new Handler();
                        Toast.makeText(QuestionActivity.this, "Time's Up", Toast.LENGTH_SHORT).show();
                        Runnable delay = new Runnable() {
                            public void run() {
                                processScreen();
                            }
                        };
                        handle.postDelayed(delay,3000);
                 }
            }

            public void onTick(long millisUntilFinished) {
                TextView time = (TextView) findViewById(R.id.timers);
                time.setText( ""+millisUntilFinished/1000);
                                }
        };
        counterTimer.start();
    }


    @Override
    public void onResume() {
        super.onResume();
    }


    @Override
    public void onClick(View arg0) 
    {
        nextBtn1.setEnabled(false);
        nextBtn2.setEnabled(false);
        nextBtn3.setEnabled(false);
        nextBtn4.setEnabled(false);
        nextBtn5.setEnabled(false);
        arg0.setEnabled(true);
        //Log.d("Questions", "Moving to next question");
        if(arg0.getId()==R.id.answer5)
        {       
            Button yes, no;
            final Dialog dialog = new Dialog(this, R.style.FullHeightDialog); //this is a reference to the style above
            dialog.setContentView(R.layout.dialog1); //I saved the xml file above as yesnomessage.xml
            dialog.setCancelable(true);

            //to set the message
            TextView message =(TextView) dialog.findViewById(R.id.tvmessagedialogtext);
            message.setText("Are you sure you want to Exit?");
            yes = (Button) dialog.findViewById(R.id.bmessageDialogYes);
            yes.setOnClickListener(new OnClickListener() {
            public void onClick(View v) 
            {
             counterTimer.cancel();
             finish();
             startActivity(new Intent(QuestionActivity.this, SplashActivity.class));             
             }
                        });

             no = (Button) dialog.findViewById(R.id.bmessageDialogNo);
             no.setOnClickListener(new OnClickListener() {
             public void onClick(View v)  
             {
             dialog.dismiss();
             nextBtn1.setEnabled(true);
             nextBtn2.setEnabled(true);
             nextBtn3.setEnabled(true);
             nextBtn4.setEnabled(true);
             }
                        });
             dialog.show();
    }

        else
        {
            if(!checkAnswer(arg0)) return;  

        /**
         * check if end of game
         */
        if (currentGame.isGameOver()){
            //Log.d("Questions", "End of game! lets add up the scores..");
            //Log.d("Questions", "Questions Correct: " + currentGame.getRight());
            //Log.d("Questions", "Questions Wrong: " + currentGame.getWrong());
            final Handler handle = new Handler();
            Runnable delay = new Runnable() {
                public void run() {
                    startActivity(new Intent(QuestionActivity.this, EndgameActivity.class));
                    finish();
                }
            };
            handle.postDelayed(delay,2000);

        }
            else
            {
                final Handler handle = new Handler();
                Runnable delay = new Runnable() {
                    public void run() {
                   startActivity(new Intent(QuestionActivity.this, QuestionActivity.class));
                   finish();
                    }
                };
                handle.postDelayed(delay,2000);
                      }
                  }
              }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        switch (keyCode)
        {
        case KeyEvent.KEYCODE_BACK :
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


    /**
     * Check if a checkbox has been selected, and if it
     * has then check if its correct and update gamescore
     */
    private boolean checkAnswer(View v) {
        final Button b = (Button) v;
        String answer = b.getText().toString();
         counterTimer.cancel();
         b.setBackgroundResource(R.drawable.ans);
         b.setEnabled(false);
        //Log.d("Questions", "Valid Checkbox selection made - check if correct");
            if (currentQ.getAnswer().equalsIgnoreCase(answer))
                {
                b.setBackgroundResource(R.drawable.ansgreen);
                //Log.d("Questions", "Correct Answer!");
                Toast.makeText(QuestionActivity.this, "Correct Answer", Toast.LENGTH_SHORT).show();
                currentGame.incrementScore();
                }

            else{
                b.setBackgroundResource(R.drawable.ansred);
                //Log.d("Questions", "Incorrect Answer!");
                Toast.makeText(QuestionActivity.this, "Incorrect Answer", Toast.LENGTH_SHORT).show();
                currentGame.decrementScore1();
                            }
            return true;
        }

    public void show() 
    {
    counterTimer.cancel();          
    }

}

person UchihaSasuke    schedule 07.10.2013    source источник
comment
Я думаю, вы можете сделать это, создав статическую переменную, которая сохранит значение вашего таймера при нажатии кнопки выхода, и вы можете продолжить с этим значением при нажатии кнопки без кнопки. Так просто.   -  person TheLittleNaruto    schedule 07.10.2013
comment
Можете ли вы помочь мне с некоторым кодом.   -  person UchihaSasuke    schedule 07.10.2013
comment
Привет! Я рассказал вам очень простой метод. ты можешь сделать это сам, чувак. Я не думаю, что вам понадобится моя помощь и в части кода. Давай, попробуй.   -  person TheLittleNaruto    schedule 07.10.2013
comment
см. здесь   -  person codeMagic    schedule 07.10.2013
comment
@Chandan проверь мой ответ и объедини его со своим кодом..   -  person Manish Srivastava    schedule 10.10.2013
comment
@Chandan, это рабочая демонстрация, сначала создайте демонстрационное приложение и проверьте, после этого внедрите его в свой код.   -  person Manish Srivastava    schedule 10.10.2013
comment
@ManishSrivastava Спасибо за ваш ответ. Но я уже провел много исследований и разработок по таймеру обратного отсчета. Но я не понимаю, почему мой таймер не останавливается во всплывающем диалоговом окне.   -  person UchihaSasuke    schedule 10.10.2013
comment
вы проверили мой код? его рабочий человек..   -  person Manish Srivastava    schedule 10.10.2013
comment
@ManishSrivastava Да!! Я проверил ваш код, но если вы видите мой код, я внедрил таймер обратного отсчета. У меня просто проблема с вызовом моей кнопки «Нет» в диалоговом окне.   -  person UchihaSasuke    schedule 10.10.2013
comment
@Chandan Я не знаю о вашем коде, что вы там сделали, но мой работает нормально, если вы хотите, чтобы этот демонстрационный проект я мог отправить вам по почте. Просто укажите свой адрес электронной почты в моем блоге.   -  person Manish Srivastava    schedule 10.10.2013
comment
@ManishSrivastava Я отправляю вам сообщение в Google. Надеюсь, вы получите .   -  person UchihaSasuke    schedule 10.10.2013


Ответы (1)


Привет, сделай что-нибудь подобное

package com.example.dialogboxwithtimer;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private TextView textTimer;
    private Button startButton;
    private Button pauseButton;
    private long startTime = 0L;
    private Handler myHandler = new Handler();
    long timeInMillies = 0L;
    long timeSwap = 0L;
    long finalTime = 0L;

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

        Button btn = (Button) findViewById(R.id.button1);

        textTimer = (TextView) findViewById(R.id.textTimer);

        startButton = (Button) findViewById(R.id.btnStart);
        startButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                startTime = SystemClock.uptimeMillis();
                myHandler.postDelayed(updateTimerMethod, 0);

            }
        });

        pauseButton = (Button) findViewById(R.id.btnPause);
        pauseButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                timeSwap += timeInMillies;
                myHandler.removeCallbacks(updateTimerMethod);

            }
        });

        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                alertMessage();
                timeSwap += timeInMillies;
                myHandler.removeCallbacks(updateTimerMethod);
            }
        });
    }

    public void alertMessage() {
        DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                case DialogInterface.BUTTON_POSITIVE:
                    // Yes button clicked

                    Toast.makeText(MainActivity.this, "Yes Clicked",
                            Toast.LENGTH_LONG).show();
                    break;

                case DialogInterface.BUTTON_NEGATIVE:
                    // No button clicked
                    // do nothing
                    startTime = SystemClock.uptimeMillis();
                    myHandler.postDelayed(updateTimerMethod, 0);

                    Toast.makeText(MainActivity.this, "No Clicked",
                            Toast.LENGTH_LONG).show();
                    break;
                }
            }
        };

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Are you sure?")
                .setPositiveButton("Yes", dialogClickListener)
                .setNegativeButton("No", dialogClickListener).show();
    }

    private Runnable updateTimerMethod = new Runnable() {

        public void run() {
            timeInMillies = SystemClock.uptimeMillis() - startTime;
            finalTime = timeSwap + timeInMillies;

            int seconds = (int) (finalTime / 1000);
            int minutes = seconds / 60;
            seconds = seconds % 60;
            int milliseconds = (int) (finalTime % 1000);
            textTimer.setText("" + minutes + ":"
                    + String.format("%02d", seconds) + ":"
                    + String.format("%03d", milliseconds));
            myHandler.postDelayed(this, 0);
        }

    };

}

А в вашем макете-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Popup" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#000000" >

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

        <Button
            android:id="@+id/btnPause"
            android:layout_width="90dp"
            android:layout_height="45dp"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/btnStart"
            android:text="Pause" />

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

</LinearLayout>

Для получения дополнительной помощи см. эти URL-адреса: http://www.androidhub4you.com/2013/04/countdown-demo-in-android-custom-timer.html и http://www.androidhub4you.com/2012/09/alert-dialog-box-or-confirmation-box-in.html

Цитата

person Manish Srivastava    schedule 10.10.2013