Service is killed in sleep mode.Why?

前端 未结 5 1322
忘了有多久
忘了有多久 2020-12-05 20:55

I\'ve read just about every Stackoverflow answer that exists on this topic, but none of them worked.

Goal: Keep my service running 24/7, all the time

5条回答
  •  盖世英雄少女心
    2020-12-05 21:40

    onDestroy() is really unreliable and won't be called often that you want. Same for onLowMemory() callbacks. There is no way to take a guaranteed callback if android decides to kill your process or if user decides to Force Stop your app.

    That's normal that than user device go to sleep mode, your service dies. Read about wakelocks. Try something like that in your service: In manifest:

    
    

    In service:

    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
        "tag");
    wakeLock.acquire();
    

    But it's rly tricky for user and totally anti-pattern in android world, cuz of battery consumption.

    Another option is to trigger service something like every 10 mins. Make pending intent on WakefulBroadcastReceiver(where you can start your service) and schedule it with alarm manager with flag RTC_WAKE_UP

提交回复
热议问题