Starting from Android 6.0 (API level 23), Android introduced Doze Mode and introduced various restrictions on background processing in Android. Android also introduced WorkManager API which makes it easy to specify asynchronous tasks and when they should run. From the Android documentation of WorkManager, we get :

Note: WorkManager is intended for tasks that require a guarantee that the system will run them even if the app exits.

I tested the same using the following program :

In MainActivity(Launcher activity of App), I create PeriodicWorkRequest with periodic interval of 15 mins( minimum allowed interval for periodic request) and handle it to workManager

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    runWorkRequest()

}

// create a PeriodicWorkRequest with Periodic Interval of 15 mins
fun runWorkRequest() {
    val periodicWorkRequestBuilder = PeriodicWorkRequest.Builder(BatteryWorker::class.java, PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS
            , TimeUnit.MILLISECONDS)
    val periodicWorkRequest = periodicWorkRequestBuilder.build()
    WorkManager.getInstance().enqueue(periodicWorkRequest)
}
}

and BackgroundWorker is as follows and logs whenever it is run :

public class BackgroundWorker extends Worker {
    @NonNull
    @Override
    public Result doWork() {

        Log.d("MyBackgroundWorker", "BackgroundWorker is Running");
        return Result.SUCCESS;
    }
}

Now if I run the above code on Api Level 28 and swiping the app off the Recent App List and turn the device screen off , Logs are printed periodically for just 40-45 mins and then the background worker is stopped. This is contrary to guaranteed execution that the documentation claims .

Does anyone has the solution for guaranteed indefinite periodic execution ( with periodic interval of 15 mins) in background in Android Oreo and above ?

0

There are 0 best solutions below