今日已更新 80 条资讯 | 累计 20052 条内容
关于我们

android doze kills your react native background tasks--here's why and how to fix it

raha 2026年06月16日 02:48 3 次阅读 来源:Dev.to

android doze kills your background tasks and nobody explains why properly been building a react native app that schedules stuff to run later. worked fine every time i tested it. shipped it, and it started missing schedules. only when the phone had been sitting idle for a while. never on my desk. took me way too long to figure out what was going on so writing it up here. what happens you schedule something for 1am. check logs next morning: 01:00:00 alarm fired 01:00:02 connected (while back grounded, 2 seconds) 01:18:xx the actual send ran the connection came up fine. in 2 seconds. while the phone was back grounded. but the code that was supposed to do something with that connection ran 18 minutes later when something else woke the phone up. why doze mode freezes javascript timers. setTimeout, setInterval, any polling loop on the js thread-all frozen. but native events (connection callbacks, lifecycle events, native module bridges) keep firing. i had a setInterval checking "are we connected yet" every second. doze froze that loop. the connection came up, nobody noticed for 18 minutes because the thing checking for it was asleep. the phone could do the work. my code just couldn't tell. stuff i tried that didn't fix it foreground service — keeps the process alive but doesn't unfreeze js timers. not the problem. more setTimeout/setInterval variations, literally the thing causing it. spent two days making the problem worse. HeadlessJS dropped in without changes compiled, never ran on newer RN. lost a few hours there. the actual fix move everything off timers. put your work directly in the event handler. instead of polling to check if you're connected: js // this is frozen by doze. don't. setInterval (() => { if ( isReady ()) doWork () }, 1000 ) do this : jsconnection . on ( ' status ' , ( state ) => { if ( state === ' connected ' ) { doWork ( job ) } }) native events survive doze. timers don't. that's the whole thing. for waking up at the right time — native AlarmManager

本文内容来源于互联网,版权归原作者所有
查看原文