I need to send a series of http requests: 1 per second during 1 minute. AFAIK it gonna impact battery usage. Is there any special strategy for handling this kind of issue ?
UPD: I have to use POST requests and here’s my POST request function:
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(3000);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
if(headers != null){
for (String key : headers.keySet()) {
connection.setRequestProperty(key, headers.get(key));
}
}
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
Log.d("response", response.toString());
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
Is there anything that could be done to improve performance in terms of the issue;
Here’s a video from Google I/O exactly about this topic:
Google I/O
In short:
Each request wakes radio from standby and turns it to full power. After request is sent it stays like this for some time and then some more time in low power state, before finally going to standby again.
If you do a series of small requests, each request will trigger radio to full power and if interval between requests is too short it will never go to standby mode.
But if you accumulate your requests (if your app doesn’t really require to display some remote data so often) and send them as a batch but not so often it will trigger radio less and save battery life.