如何在 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 的使用提供了多种选项,可将轮询功能整合到应用程序中 - 通过确保实时同步来提供动态且响应迅速的用户体验。
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

