android - 每隔一段时间在后台执行网络服务

标签 android android-background android-webservice

我需要每小时在后台执行一次网络服务

每隔一小时,将检查 Internet 是否可用,然后执行 Web 服务并更新数据。

我该怎么做?

我的后台服务

public class MyService extends Service {

   String tag="TestService";
   @Override
   public void onCreate() {
       super.onCreate();
       Toast.makeText(this, "Service created...", Toast.LENGTH_LONG).show();      
       Log.i(tag, "Service created...");
   }

   @Override
   public void onStart(Intent intent, int startId) {      
       super.onStart(intent, startId);  
       if(isInternet)
       {
           AsyTask web= new AsyTask();
           web.execute();
       }
       Log.i(tag, "Service started...");
   }
   @Override
   public void onDestroy() {
       super.onDestroy();
       Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
   }

   @Override
   public IBinder onBind(Intent intent) {
       return null;

   }

最佳答案

我们的想法是使用 AlarmManager 每小时启动一次后台服务。

将警报管理器设置为每 60 分钟启动一次后台服务。这可以在任何 Activity 中完成。

    startServiceIntent = new Intent(context,
            WebService.class);
    startWebServicePendingIntent = PendingIntent.getService(context, 0,
            startServiceIntent, 0);

    alarmManager = (AlarmManager) context
            .getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis(), 60*1000*60,
            startWebServicePendingIntent);

创建一个扩展 ServiceWebService 类,然后在 Service 的 onStartCommand() 方法中添加与服务器同步数据的方法.另外,不要忘记在 list 中声明服务。

编辑 1:

public class WebService extends Service {

   String tag="TestService";
   @Override
   public void onCreate() {
       super.onCreate();
       Toast.makeText(this, "Service created...", Toast.LENGTH_LONG).show();      
       Log.i(tag, "Service created...");
   }

   @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       super.onStart(intent, startId);  
       if(isInternet)
       {
           AsyTask web= new AsyTask();
           web.execute();
       }
       Log.i(tag, "Service started...");
   }
   @Override
   public void onDestroy() {
       super.onDestroy();
       Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
   }

   @Override
   public IBinder onBind(Intent intent) {
       return null;

   }

关于android - 每隔一段时间在后台执行网络服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24217011/

相关文章:

java - Libgdx 不会在 requestRendering 上呈现

Android Studio 3.1 - Logcat 输出已损坏

android - 将 LatLngBounds 缩小 5%

android - 如何将以下参数发送到 json webservice

java - JSON Android 解析数据时出错

android - 如果没有 Internet 连接,HttpURLConnection getResponseCode() 不会返回

android - 从 ListView 项获取文本

android - 屏幕打开时设置作业调度程序(设备未闲置)?

android - 缩放图像在背景可绘制中保持其纵横比

android - 您可以在您的 Android 应用程序中同时运行两个后台服务吗?