How do i make a simple timer in java with a button

2019-08-30 05:49发布

问题:

In android studio in the MainActivity in the onCreate i did:

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

In strings.xml i added:

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

In activity_main.xml i added:

<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" />

In the activity_main designer it looks like:

In the MainActivity i have a touch event:

@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;
        }

What i want to do is when in the touch event it's true after this line:

if (is_start == true)

Start the timer and display on the timerValueRecord the time running including milliseconds seconds and minutes until the user touch again and then it's getting to the stop part and then to stop the timer.

The problem is how to build the timer at all and how to stop and start it.

回答1:

You can try this below Code:

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);
        }

    };

You can use StartTimer() and StopTimer() function where you want to start or stop the timer:



回答2:

try this way

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();

                        }

                    });

                }

            };

        }

    }