如何使用单击按钮启动/停止计时器在java中创建一个简单的计时器?

时间:2015-11-16 11:17:00

标签: java android android-studio timer

在onCreate的MainActivity中的android studio中我做了:

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

在strings.xml中,我添加了:

<string name="timerValRecord">Recording Time: 00:00:00</string>

在activity_main.xml中我添加了:

<TextView
        android:id="@+id/timerValueRecord"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textSize="20sp"
        android:textColor="#000000"
        android:layout_marginTop="315dp"
        android:text="@string/timerValRecord" />

在activity_main设计器中,它看起来像:

Design

在MainActivity中,我有一个触摸事件:

@Override
        public boolean onTouchEvent(MotionEvent event)
        {
            float eventX = event.getX();
            float eventY = event.getY();

            float lastdownx = 0;
            float lastdowny = 0;

            switch (event.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    lastdownx = eventX;
                    lastdowny = eventY;

                    Thread t = new Thread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            byte[] response = null;
                            if (connectedtoipsuccess == true)
                            {

                                if (is_start == true)
                                {
                                    response = Get(iptouse + "start");
                                    is_start = false;
                                } else
                                {
                                    textforthespeacch = "Recording stopped and preparing the file to be shared on youtube";
                                    MainActivity.this.initTTS();
                                    response = Get(iptouse + "stop");
                                    is_start = true;
                                    startuploadstatusthread = true;
                                    servercheckCounter = 0;
                                }
                                if (response != null)
                                {
                                    try
                                    {
                                        a = new String(response, "UTF-8");

                                        MainActivity.this.runOnUiThread(new Runnable()
                                        {
                                            @Override
                                            public void run()
                                            {
                                                if (a.equals("Recording started"))
                                                {
                                                    status1.setText("Recording");
                                                }
                                                if (a.equals("Recording stopped and preparing the file to be shared on youtube"))
                                                {
                                                    status1.setText("Recording Stopped");
                                                }
                                            }
                                        });
                                        textforthespeacch = a;
                                        MainActivity.this.initTTS();
                                    } catch (UnsupportedEncodingException e)
                                    {
                                        e.printStackTrace();
                                    }
                                    Logger.getLogger("MainActivity(inside thread)").info(a);
                                }
                            }
                        }
                    });
                    t.start();
                    return true;
                case MotionEvent.ACTION_MOVE:
                    break;
                case MotionEvent.ACTION_UP:                    
                    break;
                default:
                    return false;
            }
            return true;
        }

我想做的是在触摸事件中,在这一行之后是真的:

if (is_start == true)

启动计时器并在timerValueRecord上显示运行的时间,包括毫秒秒和分钟,直到用户再次触摸,然后它到达停止部分,然后停止计时器。

问题是如何构建计时器以及如何停止和启动计时器。

2 个答案:

答案 0 :(得分:2)

试试这种方式

public class AndroidTimerTaskExample extends Activity {



        Timer timer;

        TimerTask timerTask;



        //we are going to use a handler to be able to run in our TimerTask

        final Handler handler = new Handler();



        @Override

        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);

        }



        @Override

        protected void onResume() {

            super.onResume();



            //onResume we start our timer so it can start when the app comes from the background

            startTimer();

        }



        public void startTimer() {

            //set a new Timer

            timer = new Timer();



            //initialize the TimerTask's job

            initializeTimerTask();



            //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms

            timer.schedule(timerTask, 5000, 10000); //

        }



        public void stoptimertask(View v) {

            //stop the timer, if it's not already null

            if (timer != null) {

                timer.cancel();

                timer = null;

            }

        }



        public void initializeTimerTask() {



            timerTask = new TimerTask() {

                public void run() {



                    //use a handler to run a toast that shows the current timestamp

                    handler.post(new Runnable() {

                        public void run() {

                            //get the current timeStamp

                            Calendar calendar = Calendar.getInstance();

                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");

                            final String strDate = simpleDateFormat.format(calendar.getTime());



                            //show the toast

                            int duration = Toast.LENGTH_SHORT;  

                            Toast toast = Toast.makeText(getApplicationContext(), strDate, duration);

                            toast.show();

                        }

                    });

                }

            };

        }

    }

答案 1 :(得分:2)

您可以尝试以下代码:

public class ShowTimer {


    private long startTime = 0L;
    private Handler customHandler = new Handler();
    long timeInMilliseconds = 0L;
    long timeSwapBuff = 0L;
    long updatedTime = 0L;

    public void StartTimer() {

        startTime = SystemClock.uptimeMillis();
        customHandler.postDelayed(updateTimerThread, 0);
    }

    public void StopTimer() {
         timeSwapBuff += timeInMilliseconds;
        customHandler.removeCallbacks(updateTimerThread);
    }

    private Runnable updateTimerThread = new Runnable() {

        public void run() {

            timeInMilliseconds = SystemClock.uptimeMillis() - startTime;

            updatedTime = timeSwapBuff + timeInMilliseconds;

            int secs = (int) (timeInMilliseconds / 1000);
            int mins = secs / 60;
            secs = secs % 60;
            int hours = mins / 60;
            mins = mins % 60;
            //int milliseconds = (int) (updatedTime % 1000);
            //+ ":" + String.format("%03d", milliseconds)
            String timer = "" + String.format("%02d", hours) + ":" + String.format("%02d", mins) + ":" + String.format("%02d", secs);
           //set yout textview to the String timer here
            customHandler.postDelayed(this, 1000);
        }

    };

您可以使用StartTimer()StopTimer()功能来启动或停止计时器: