So what i want to do (if posible) is to execute a function after a certain time even if the app gets closed by the user, what the function does is send a mqtt message to a server. I heard about AlarmManager and BackgroundReciver, but i dont know if that can play a whole function. Can someone tell me if it's possible?
CodePudding user response:
In android, you can try to use Services to achieve this.
And from document Background Execution Limits in Android 8.0,we know that
Starting in Android 8.0 (API level 26), an Android application no longer have the ability to run freely in the background. When in the foreground, an app can start and run services without restriction. When an application moves into the background, Android will grant the app a certain amount of time to start and use services. Once that time has elapsed, the app can no longer start any services and any services that were started will be terminated. At this point it is not possible for the app to perform any work. Android considers an application to be in the foreground if one of the following conditions are met:
There is a visible activity (either started or paused).
The app has started a foreground service.
Another app is in the foreground and is using components from an app that would be otherwise in the background. An example of this is if
Application A, which is in the foreground, is bound to a service
provided by Application B. Application B would then also be
considered in the foreground, and not terminated by Android for being in the background.
There are some situations where, even though an app is in the background, Android will wake up the app and relax these restrictions for a few minutes, allowing the app to perform some work:
- A high priority Firebase Cloud Message is received by the app.
- The app receives a broadcast.
- The application receives and executes a PendingIntent in response to a Notification.
You can also refer to https://robertohuertas.com/2019/06/29/android_foreground_services/.