Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Timer 定時輪詢實作:定期抓取伺服器時間的完整範例

編輯:關於 Android 程式設計

這個範例示範如何用 Timer 做定時輪詢:按下開始鈕之後,每 2 秒向後端請求一次時間,透過 Handler 把結果回送到主執行緒更新畫面,按下停止鈕則取消排程。

一、後端:用 PHP 回傳目前時間

最簡單的服務端只需要一行:

<?php
    echo date('Y-m-d H:i:s');
?>

二、版面配置 activity_main.xml

畫面上放兩顆按鈕(開始、停止)與一個顯示文字的 TextView:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btn_click"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button Start" />

    <TextView
        android:id="@+id/tv_show"
        android:layout_below="@id/btn_click"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:textSize="28sp" />

    <Button
        android:id="@+id/btn_stop"
        android:layout_below="@id/tv_show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button Stop" />
</RelativeLayout>

三、MainActivity.java

其中 HttpHelper.getStringFromNet2(param) 是網路請求的輔助方法,實作方式可參考本站另一篇 HttpHelper 的說明。

public class MainActivity extends Activity {
    private Button btnClick = null;
    private Button btnStop = null;
    private TextView tvShow = null;
    private String info = "";
    private Timer timer = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnClick = (Button) findViewById(R.id.btn_click);
        btnStop = (Button) findViewById(R.id.btn_stop);
        tvShow = (TextView) findViewById(R.id.tv_show);

        timer = new Timer();

        btnClick.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                // 延遲 100ms 後啟動,之後每 2000ms 執行一次
                timer.scheduleAtFixedRate(new MyTask(), 100, 2000);
            }
        });

        btnStop.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                timer.cancel();
            }
        });
    }

    Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (info != "") {
                tvShow.setText(info);
            }
        }
    };

    private class MyTask extends TimerTask {
        public void run() {
            String param = "https://192.168.0.116/android/time.php";
            info = HttpHelper.getStringFromNet2(param);
            myHandler.obtainMessage(100).sendToTarget();
        }
    }
}

關鍵設計說明

  • scheduleAtFixedRate(task, 100, 2000) 的第二個參數是首次執行的延遲毫秒數,第三個參數是後續每次執行的間隔。
  • TimerTask 執行在自己的背景執行緒,不能直接操作 UI,因此必須透過 Handler 把資料送回主執行緒,再由 handleMessage 更新 TextView。
  • 記得在 onDestroy 或離開頁面前呼叫 timer.cancel(),避免背景任務持續執行造成資源浪費。
  • 别忘了在 AndroidManifest.xml 加上 android.permission.INTERNET 權限。

四、執行結果

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved