Android 加入時間顯示

摘要:Android 加入時間顯示

Android 加入時間顯示,讀取系統時間,並每秒更新在TextView上

Source code


package com.example.system_utc_time;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Main extends Activity {
    private TextView mSystemTime, mUtcTime;
    private Button mButton;
    private Calendar mCalendar;
    private String str;
    private SimpleDateFormat df;
    private long startTime;
    private Handler handler = new Handler();    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setViews();
        operation();
    }

    public void setViews(){
        mSystemTime = (TextView)findViewById(R.id.tv2);
        mUtcTime = (TextView)findViewById(R.id.tv4);
        mButton = (Button)findViewById(R.id.btn);
    }
    
    public void operation(){        
        mButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                mUtcTime.setText("ABCDE");
                mSystemTime.setText(""+ str);
            }       
        });
        
       
        startTime = System.currentTimeMillis(); //取得目前時間
        handler.removeCallbacks(updateTimer);//設定定時要執行的方法  
        handler.postDelayed(updateTimer, 500);//設定Delay的時間
    }

    //固定要執行的方法
    private Runnable updateTimer = new Runnable() {
        public void run() {
            final TextView time = (TextView) findViewById(R.id.tv5);
            handler.postDelayed(this,500);
            mCalendar = Calendar.getInstance();
            df = new SimpleDateFormat("yyyy/MM/dd  HH:mm:ss");
            str = df.format(mCalendar.getTime());
            time.setText(str);

        }
    }; 
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}