Search code examples
androidmultithreadingservicewakelock

How can I periodically run a service/thread in background even when the screen is locked?


I'm working on an app that can check web data every half an hour and I need to ensure it keeps running as long as the power is on. For now, the structure of my app is like this:

  1. main_activity:
    AlarmManager in onCreate()
  2. alarm_receiver:
    start_service acquire partial_wl for the service
  3. service:
    get network data using StrictMode pop activity_2 if the data is expected
  4. activity_2:
    vibration button to exit(activity_2.this.finish())

But in testing I find the service will stop(be killed) after the first 30 mins. In addition, if I start a thread for networking in service instead of using StrictMode, it will be killed in 5mins after the screen is locked.

Hope someone could give a suggestion for this. It's truly disturbing. Many thanks.


Solution

  • I have changed a few things and it works well now.

    1.As my phone is 4.4.2(api=19), alarmmanager.setrepeating is inexact. So I turn to use .setExact (new method of .set()) and reschedule the alarm at the end of AsyncTask(network) in Service.

    2.Make wakelock instance global, acquiring it in AlarmReceiver and releasing at the end of the AsyncTask. I used to put .release() in onDestroy() which releases the lock before the task is done.

    3.There is a setting about protected-background applications in my phone and I didn't turn it on. That can allow system kill the application and disable the alarm manager.