1

I'm developing and Android application on CodenameOne that needs to send a web request every 5 minutes even when minimized. How can I achieve this behavior in order to prevent that the request get stopped or paused by the OS?

Bryan Herbst
  • 66,602
  • 10
  • 133
  • 120
user2416072
  • 59
  • 1
  • 3

4 Answers4

0

You cant do that from the activity, you'll need to create background service.

http://developer.android.com/training/run-background-service/create-service.html

Broak
  • 66
  • 1
  • 7
0

Use AlarmManager to set up your every-five-minute operation. Have it trigger a BroadcastReceiver, which in turn passes control to my WakefulIntentService (or your own IntentService that handles the WakeLock, that you will need so that the device stays awake while you do your work). Have the service do the "web request".

This is still not 100% guaranteed:

  • The user can Force Stop you from Settings, in which case your alarms are gone and nothing will happen until the user manually runs your app again

  • The user might block alarms from firing on certain devices, like various SONY Xperia models, that offer "stamina mode" or the equivalent

However, it is the best that you are going to get, short of rolling your own Android OS version.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

The other guys answers are correct that you need to create a service but they somehow ignored the mention of Codename One.

Under Codename One you need to create a native directory for android and just place the service source code there (just use a blank service class that doesn't really do anything). Then you need to add to the build arguments the option android.xapplication where you would state the service XML attributes.

Having said that what you are trying to do is VERY wrong and you shouldn't do it in Android! You will drain the battery life from the device in no time and the service will be killed by the OS eventually (since it will be a battery drain). The solution is to send a push notification to the device to wake up the application.

Shai Almog
  • 51,749
  • 5
  • 35
  • 65
  • Last paragraph, haha, very wrong huh?.What do you think all these fine Google apps do? Calling home, all the time! But I agree, bad idea. – Codebeat Dec 27 '16 at 08:32
  • Nope, they don't do that. I suggest reading up on how they persist connection resources thru a common pool that intelligently disconnects radio networking when necessary... That's why we have API's like push notification etc. – Shai Almog Dec 27 '16 at 15:10
0

In Android 9 and newer you can prevent your App falling asleep with a battery setting.
Long click on your App -> App info -> battery -> optimize battery consumption
Here add your App from the list.


Hint: maybe the menu entries have a different name, depending on your phone.

SJX
  • 1,071
  • 14
  • 15