首页 > 文章列表 > 在Android中实现轮询的方法是什么?

在Android中实现轮询的方法是什么?

android 实现方法 轮询
243 2023-09-09

Android 中的轮询是一项关键技术,它允许应用程序定期从服务器或数据源检索和更新信息。通过实施轮询,开发人员可以确保实时数据同步并向用户提供最新的内容。它涉及定期向服务器或数据源发送请求并获取最新信息。

Android提供了定时器、线程、后台服务等多种机制来高效地完成轮询。这使开发人员能够设计与远程数据源保持同步的响应式动态应用程序。本文探讨了如何在 Android 中实现轮询。它涵盖了实现此功能所涉及的关键注意事项和步骤。

轮询

定期检查更新并从服务器或源检索数据的过程在 Android 中称为轮询。通过按设定的时间间隔发送重复的请求,该技术可以使写入的内容与最新的更改保持同步,并提供实时同步,以确保在 Android 应用程序中及时传递准确的信息。

方法

有多种方法可以使用 Java 在 Android 中实现轮询。以下是三种常用的方法:

  • TimerTask 和计时器

  • 处理程序和可运行对象

  • AlarmManager 和 BroadcastReceiver

TimerTask 和计时器

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;
      }
   }
}

输出

在Android中实现轮询的方法是什么?

处理程序和可运行程序

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();
   }
}

输出

在Android中实现轮询的方法是什么?

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中实现轮询的方法是什么?

结论

要使用来自服务器的新内容更新 Android 应用程序,开发人员可以利用轮询,这使得应用程序能够定期获取数据或更新。 TimerTask 和 Timer、Handler 和 Runnable 或 AlarmManager 和 BroadcastReceiver 的使用提供了将轮询功能合并到应用程序中的多种选项 - 通过确保实时同步提供动态和响应式的用户体验。