让另一节课来计算时间

时间:2015-09-17 08:48:16

标签: android class time

创建一个新的类来计算时间我遇到了问题。这是我的代码:

Button btcheck = (Button)findViewById(R.id.btcheck);

btcheck.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v){
        Time aa = new Time();
        aa.RunTime();                   
    }           
});

public class Time extends MainActivity {

    public void RunTime() {     
        startTime = SystemClock.uptimeMillis();
        customHandler.postDelayed(updateTimerThread, 0);            
    }

    public Runnable updateTimerThread = new Runnable() {
        public void run() {

            updatedTime = SystemClock.uptimeMillis() - startTime;

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

            stime="" + mins + ":" + String.format("%02d", secs) + ":" + String.format("%03d", milliseconds);                            

            txttime.setText(stime + " ");
            customHandler.postDelayed(this, 0);     
    };
}

然而它并没有像我期望的那样起作用。希望你帮帮我。

1 个答案:

答案 0 :(得分:0)

您可以使用扩展AsyncTask而不是MainActivity。这样您就不会创建新的活动回溯日志,并且可以在不与线程冲突的情况下更新UI。

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 ] + " " );
        }
    }