1. 程式人生 > >Android 獲取時間實時更新UI

Android 獲取時間實時更新UI

第一種:使用Handler獲取

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        time= (TextView) findViewById(R.id.time);
        new TimeHandler().start();
//        getTime()//第二種方法
    }

    class TimeHandler extends Thread{
        @Override
public void run() { super.run(); do{ try { Thread.sleep(1000); Message message=new Message(); message.arg1=5; handler.sendMessage(message); } catch
(Exception e){ } }while (true); } } private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: long
sysTime = System.currentTimeMillis(); CharSequence sysTimeStr = DateFormat.format("hh:mm:ss", sysTime); time.setText(sysTimeStr); //更新時間 break; default: break; } } }; /** * 第二種方式 使用Handler * */ private Handler handlers=new Handler(); private void getTime(){ Timer timer=new Timer(); TimerTask timerTask=new TimerTask() { @Override public void run() { SimpleDateFormat format=new SimpleDateFormat("HH:mm"); final String times=format.format(new Date()); handler.post(new Runnable() { @Override public void run() { time.setText(times); } }); } }; timer.schedule(timerTask,0,1000); }

第二種:使用服務

 public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        init();
        //每隔一秒傳送一次廣播
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                sendTimeChangedBroadcast();
            }
        },1000,1000);
    }

    private void init() {
        timer=new Timer();
        sdf = new SimpleDateFormat("yyyy年MM月dd日 "+"hh:mm:ss");
        timeIntent = new Intent();
        bundle = new Bundle();
    }

    /**
     * 傳送廣播,通知UI層時間已改變
     */
    private void sendTimeChangedBroadcast(){
        bundle.putString("time", getTime());
        timeIntent.putExtras(bundle);
        timeIntent.setAction(TimeServiceActivity.TIME_CHANGED_ACTION);
        //傳送廣播,通知UI層時間改變了
        sendBroadcast(timeIntent);
    }
    /**
     * 獲取最新系統時間
     * @return
     */
    private String getTime(){
        return sdf.format(new Date());
    }