-1

I have programmed an app which uses a handler. Inside the handler there are some network operations. The handler has an interval of min*1000*60 ms. I used the handler with min=5, so it should repeat after five minutes. But this is the result of my check:

First Handler:

16:20:22
16:25:23
17:01:52
17:13:07
17:20:19
17:25:55

Second Handler:

16:20:26
16:25:26
17:01:35
17:12:51
17:20:02
17:25:37

Third Handler:

16:24:58
16:31:59
17:12:43
17:19:54
17:25:30

All Handlers are running in separate Services. The screen is turned off. Do you have any ideas or alternatives to a Handler in Android?

The code of the handlers is so simple:

handler.postDelayed(new Runnable() {
            public void run() {
            // network operations
            }
        }, interval);
4

2 回答 2

1

首先,假设您创建了Handlervia new Handler(),它将在主应用程序线程上完成它的工作。不要在主应用程序线程上进行网络 I/O。这也可能是你漂移的根源。

其次,您很可能不需要三项服务。通常,您需要一项服务。三项服务只会使您的应用程序更加复杂,而不会为用户带来任何附加价值。

第三,您Handler只能在设备唤醒时工作,我不知道这是否是可接受的限制。

第四,使用 aHandler意味着您的服务将无限期地运行,而用户不喜欢这样。仅当您的服务积极为用户提供价值时,它们才会被记住

因此,实现这一点的更好方法是AlarmManager用于您的预定事件。如果您不需要在设备休眠时处理事件,则AlarmManager可以直接将控制权交给您的服务。理想情况下,这将是一个IntentService, 以便该服务会自动为您提供一个后台线程,并且该服务将在工作完成时自动关闭。

如果您需要在设备处于睡眠状态时处理事件,请让用户控制事件周期,包括“不执行任何操作”选项,如每 5 分钟唤醒设备进行网络 I/O会对电池不利。然后,使用aWakefulBroadcastReceiveraWakefulIntentService安排在保持设备唤醒的同时完成工作。

于 2013-09-04T16:02:43.107 回答
0

使用SheduledThreadPoolExecutor而不是处理程序。它具有scheduleAtFixedRate功能,可以完全满足您的需求。而且根本没有处理程序)

于 2013-09-04T16:28:16.527 回答