1

I am calling a web service HTTPS connection from Service class which is called by alarm manager in every 1 min.When i start service it is working fine i am getting response from web service until device gets in sleep mode.when device's screen gets off, on next web service call i am getting this error-

   com.turbomanage.httpclient.HttpRequestException: java.net.SocketTimeoutException: connect timed out

it will continue throw this exception until i wakeup the device.When device get wakeup the webservice start getting response from server and i am not getting exception then. So please anyone tell me what could be the problem.The testing device is Nexsus 5X.

shyam002
  • 237
  • 1
  • 5
  • 19

2 Answers2

2

I am calling a web service HTTPS connection from Service class which is called by alarm manager in every 1 min

That will not work on Android 6.0+, unless your app is on the battery optimization whitelist. Doze mode will stop most of your alarms, and on those cases where you do get control, you may not have Internet access.

Also, bear in mind that waking up the device every minute to go and perform network I/O will drain the battery, which is why Android 6.0 introduced Doze mode in the first place.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • so what is the solution then ? – shyam002 Aug 05 '17 at 14:11
  • @shyam002: I do not know what the problem is. There is no guarantee that you will have an Internet connection at any point in time, for all sorts of reasons (e.g., airplane mode). You should be handling this the same as you would for any other lack of connectivity. – CommonsWare Aug 05 '17 at 14:15
  • @shyam002: If you wish to maximize the chances that you will have an Internet connection in sleep mode on Android 6.0+, ask the user to add your app to the battery optimization whitelist. On a Nexus 5X running Android 7.1.1, that is Settings > Apps > (gear icon) > Special access > Battery optimization. However, you need to recognize that users may not do this, or they may change their mind and remove your app from this list if they do not like how much battery your app uses. – CommonsWare Aug 05 '17 at 14:17
0

Optimize for Doze and App Standby

https://developer.android.com/training/monitoring-device-state/doze-standby

And code for ignore battery optimize

PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
if (powerManager.isIgnoringBatteryOptimizations(getPackageName())) {
    intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
}
else {
    intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
    intent.setData(Uri.parse("package:" + getPackageName()));
    startActivity(intent);
}
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135