如何在Android中實現輪詢?
Android中的輪詢是一種關鍵技術,允許應用程式定期從伺服器或資料來源檢索和更新資訊。透過實現輪詢,開發人員可以確保即時資料同步並向用戶提供最新的內容。它涉及定期向伺服器或資料來源傳送請求並獲取最新資訊。
Android提供各種機制,例如計時器、執行緒和後臺服務,以有效地完成輪詢。這使開發人員能夠設計響應迅速且動態的應用程式,這些應用程式與遠端資料來源保持同步。本文探討了如何在Android中實現輪詢。它涵蓋了實現此功能的關鍵考慮因素和步驟。
輪詢
定期檢查更新並從伺服器或資料來源檢索資料,這就是Android中所謂的輪詢。透過以設定的時間間隔重複傳送請求,此技術使書面內容保持最新,並提供即時同步,以確保在Android應用程式中及時準確地傳遞資訊。
方法
使用Java在Android中實現輪詢有幾種方法。以下是三種常用的方法:
TimerTask和Timer
Handler和Runnable
AlarmManager和BroadcastReceiver
TimerTask和Timer
Java TimerTask和Timer類可用於在Android上實現輪詢。只需建立一個TimerTask物件來定義要重複執行的任務,然後使用Timer物件使用scheduleAtFixedRate()方法以固定的時間間隔對其進行排程。這確保您的任務始終如一地執行,定期執行更新或獲取資料。
演算法
建立一個TimerTask物件,定義定期執行的任務。
建立一個Timer物件,並使用scheduleAtFixedRate()方法以固定的時間間隔排程TimerTask。
示例
//MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
private PollingManager pollingManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pollingManager = new PollingManager(1000); // Interval of
1000 milliseconds (1 second)
pollingManager.startPolling();
}
@Override
protected void onDestroy() {
super.onDestroy();
pollingManager.stopPolling();
}
}
// PollingManager.java
import java.util.Timer;
import java.util.TimerTask;
public class PollingManager {
private Timer timer;
private TimerTask timerTask;
private long interval;
public PollingManager(long interval) {
this.interval = interval;
}
public void startPolling() {
timer = new Timer();
timerTask = new TimerTask() {
@Override
public void run() {
// Perform polling logic here
// This code will be executed periodically based on the
interval
System.out.println("Polling...");
}
};
timer.scheduleAtFixedRate(timerTask, 0, interval);
}
public void stopPolling() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
}
輸出

Handler和Runnable
Handler和Runnable組合提供了另一種在Android中實現輪詢的方法。在主執行緒中建立一個Handler物件來發布和處理訊息。然後,建立一個執行輪詢任務的Runnable物件。使用Handler的postDelayed()方法以所需的時間間隔排程Runnable。此機制允許您控制輪詢任務的時間安排並定期執行它。
演算法
在主執行緒中建立一個Handler物件來發布和處理訊息。
建立一個執行輪詢任務的Runnable物件。
使用Handler的postDelayed()方法以所需的時間間隔排程Runnable。
示例
import android.os.Handler;
public class PollingExample {
private static final int POLLING_INTERVAL = 5000; // 5 seconds
private Handler handler = new Handler();
private Runnable pollingRunnable = new Runnable() {
@Override
public void run() {
// Perform polling task here
System.out.println("Polling task executed!");
// Schedule the next polling iteration
handler.postDelayed(this, POLLING_INTERVAL);
}
};
public void startPolling() {
// Start the initial polling iteration
handler.postDelayed(pollingRunnable, POLLING_INTERVAL);
}
public void stopPolling() {
// Stop the polling
handler.removeCallbacks(pollingRunnable);
System.out.println("Polling stopped!");
}
public static void main(String[] args) {
PollingExample example = new PollingExample();
example.startPolling();
// Let the program run for some time to observe the output
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
example.stopPolling();
}
}
輸出

AlarmManager和BroadcastReceiver
為了觸發輪詢任務,可以使用AlarmManager和BroadcastReceiver方法。首先,設定一個重複的鬧鐘。然後,註冊一個BroadcastReceiver來接收鬧鐘事件,並透過使用PendingIntent建立Intent來指定操作。最後,透過使用AlarmManager的setRepeating()或setInexactRepeating()方法,確保即使在後臺或應用程式未執行時該方法也能執行。
演算法
註冊一個BroadcastReceiver來接收鬧鐘事件。
建立一個Intent和PendingIntent來觸發BroadcastReceiver。
使用AlarmManager使用setRepeating()或setInexactRepeating()方法設定重複鬧鐘。
示例
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class PollingReceiver extends BroadcastReceiver {
private static final int POLLING_INTERVAL = 5000; // 5 seconds
@Override
public void onReceive(Context context, Intent intent) {
// Perform polling task here
System.out.println("Polling task executed!");
}
public void startPolling(Context context) {
AlarmManager alarmManager = (AlarmManager)
context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, PollingReceiver.class);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), POLLING_INTERVAL, pendingIntent);
}
public void stopPolling(Context context) {
AlarmManager alarmManager = (AlarmManager)
context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, PollingReceiver.class);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.cancel(pendingIntent);
System.out.println("Polling stopped!");
}
}
輸出

結論
為了使用來自伺服器的新內容更新Android應用程式,開發人員可以使用輪詢,這使應用程式能夠定期獲取資料或更新。使用TimerTask和Timer、Handler和Runnable或AlarmManager和BroadcastReceiver提供了多種將輪詢功能整合到應用程式中的選項——透過確保即時同步提供動態且響應迅速的使用者體驗。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP