当前位置: 代码迷 >> Android >> android服务中的定时循环未按预期执行
  详细解决方案

android服务中的定时循环未按预期执行

热度:80   发布时间:2023-08-04 12:10:03.0

我正在创建我的第一个服务,该服务需要每5分钟执行一次操作。 我得到的结果接近他们应该不应该得到的结果。 我正在尝试每5分钟将时间记录到我的Firebase中。

结果:

-K1T1GtyTfdJM_3dIvHe: "Date: 25, time:21:07"
-K1T60t8YEPghiqUpPnt: "Date: 25, time:21:27"
-K1T60tDPRg7RmdDUwjG: "Date: 25, time:21:27"
-K1T60taul-iMquEQUM6: "Date: 25, time:21:27"
-K1T60tbdyvIey9SINdm: "Date: 25, time:21:27"
-K1TBM_qDLQLnaeNB4x-: "Date: 25, time:21:50"
-K1TBM_sWiIkI0e1usqS: "Date: 25, time:21:50"
-K1TBM_sWiIkI0e1usqT: "Date: 25, time:21:50"
-K1TBM_tH8S4cTPUQ-NV: "Date: 25, time:21:50"
-K1TBcxo0UYS4h-uw1pA: "Date: 25, time:21:52"
-K1TGXIDMPPlyM5byhy9: "Date: 25, time:22:13"
-K1TGXOS7j8U_yeBh5zl: "Date: 25, time:22:13"
-K1TGXOS7j8U_yeBh5zm: "Date: 25, time:22:13"
-K1TGXOTvKvrmCSpCjWw: "Date: 25, time:22:13"

服务:

public class locationCheckService extends IntentService {

public locationCheckService() {
    super("locationCheckService");
}


@Override
protected void onHandleIntent(Intent intent) {
    System.out.println("Service running");
    final Firebase testRef = new Firebase("https://myurl.firebaseio.com/androidTest");


    new Timer().scheduleAtFixedRate(new TimerTask(){
        @Override
        public void run(){
            Calendar now = Calendar.getInstance();
            int hours = now.get(Calendar.HOUR);
            int minutes = now.get(Calendar.MINUTE);
            int ampm = now.get(Calendar.AM_PM);
            int hours24 = now.get(Calendar.HOUR_OF_DAY);
            int date = now.get(Calendar.DATE);
            String fireTime = "Date: " + date + ", time:" + String.format("%02d:%02d", hours24, minutes);
            String time = String.format("%02d:%02d", hours, minutes);
            if(ampm == 0){
                Log.i("tag", time + " am");

            } else {
                Log.i("tag", time + " pm");
            }
            Log.i("fire", fireTime);
            testRef.push().setValue(fireTime);
        }
    },0,300000);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
    return super.onStartCommand(intent,flags,startId);
}
}

如您所见,它确实被触发了正确的次数,但是似乎错过了3-4次,然后尝试赶上。 有人可以向我解释为什么会这样和/或是否有办法解决这个问题?

此外,当设备连接到PC进行调试并且打开了应用程序时,它的确运行正常。

作为一项节能功能,如果没有应用程序要求其保持开机状态(通常通过WakeLock),您的设备将进入睡眠状态。 这意味着所有CPU均已暂停,并且没有进程可以运行。 当设备由于某种原因唤醒时,您的过程将有机会赶上一点。

设备在充电时永远不会进入睡眠状态,这就是为什么在连接到计算机后看不到问题的原因。

您应该能够使用或可靠地运行代码。

请注意,每5分钟唤醒一次设备可能会对电池寿命产生负面影响。

  相关解决方案