I'm trying to make an android app that fires a background intent to "ping" a server with a post request about every 2 minutes (by default, interval is user-configurable).
I absolutely need to avoid the service running when the phone is not in active use, and I need it to not defer the service like an AlarmManager would. If it tries to fire when the phone screen is off, I want it to silently fail.
Is this possible, and if so what parts of the API do I need to look at to get started on it?
Please note, I do know the rules of asking a good question. The reason I'm not listing what I tried is I don't know where to start.
CodePudding user response:
You need to create a broadcast receiver to listen to the intents sent by the system. Something like in the code below but adjusted to your solution
@Override
public void onReceive(final Context context, final Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
}
}
More information about the Broadcast receivers can be found here: https://developer.android.com/guide/components/broadcasts
I hope this will be a good starting point for you.