Skip to content Skip to sidebar Skip to footer

Make Another Class To Count Time

I have a problem with create a new class to count time. This is my code: Button btcheck = (Button)findViewById(R.id.btcheck); btcheck.setOnClickListener(new View.OnClickListener()

Solution 1:

You could use extends AsyncTask instead of MainActivity. This way you're not creating a new activity back log and you can update your UI without conflicting with your threading.

private Handler handler = new Handler( );
    public long startTime;
    public void onClick(View v){
        switch( v.getId( ) ){
            case R.id.btcheck:
                this.startTime = SystemClock.uptimeMillis();
                startTimer( );
                break;
        }
    }
    private void startTimer( ){
        startRunnable( );
    }

    private Runnable startRunnable( )
    {
        new Runnable( )
        {
            @Override
            public void run( )
            {
                new Time( startTime ).execute( );
                long timer = 1000;
                handler.postDelayed( startRunnable( ), timer );
            }
        };
        return null;
    }

    class Time extends AsyncTask< String, String, String >
    {
        private long startTime;
        private long updatedTime;

        public Time( long startTime )
        {
            this.startTime = startTime;
        }

        @Override
        protected void onPreExecute( )
        {
        }

        @Override
        protected void onPostExecute( String result )
        {
        }

        @Override
        protected String doInBackground( String... param )
        {
            updatedTime = SystemClock.uptimeMillis( ) - startTime;

            int secs = ( int ) ( updatedTime / 1000 );
            int mins = secs / 60;
            secs = secs % 60;
            int milliseconds = ( int ) ( updatedTime % 1000 );

            publishProgress( "" + mins + ":" + String.format( "%02d", secs ) + ":" + String.format( "%03d", milliseconds ) );
            return null;
        }

        @Override
        protected void onProgressUpdate( String... values )
        {
            txttime.setText( values[ 0 ] + " " );
        }
    }

Post a Comment for "Make Another Class To Count Time"