我正在创建我的第一项服务,需要每5分钟做一次。我得到的结果接近他们应该不完全的结果。我试着每5分钟将时间记录到我的火力基地。
结果:
-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进行调试并且应用程序已打开时,它确实正常运行。
答案 0 :(得分:0)
作为省电功能,如果没有应用请求它保持运行(通常通过WakeLock),您的设备将进入休眠状态。这意味着所有CPU都暂停,并且没有进程可以运行。当设备因某种原因被唤醒时,您的过程有机会赶上一点。
设备在充电时从不进入睡眠状态,这就是为什么连接到计算机时没有看到问题的原因。
您应该能够使用JobScheduler或AlarmManager可靠地运行代码。
请注意,每5分钟唤醒一次设备可能会对电池寿命产生负面影响。