I have an android app, that gets some information from the internet. Usually it gets it through my server, which collets the data and sends it via GCM, but there is a certain scenario, where it goes into a fallback mode, when it starts a service that polls a 3rd party REST API every 2 seconds. I wonder what's the right way to implement this (pros/cons)
1st way: My 1st implementation was to use an AlarmManager and a BroadcastReceiver. In the BroadcastReceiver I locked PowerManager.WakeLock and WifiManager.WifiLock, then when I got the response I unlocked them, and set up the AlarmManager for 2 seconds.
Then I thought that probably all I achieved by this is that my app hardly shows up as a battery consumer in android Settings, while basically it does drain the battery, as probably the WiFi is not disconnected for 2 seconds, then reconnected. Also noticed that because of the BroadcastReceiver I create a new instance of my RestClient every 2 seconds, then garbage collect it. So I am thinking of changing the implementation:
2nd way: lock PowerManager, WifiManager when I start the PollService (this will cause my app to show up in battery consumption with a serious percentage, but does it really draw more battery, or does it only "correct" the report?)
Now what should be the way to wait for 2 seconds? Should I continue to use the AlarmManager and garbage collection... Or should I do something like:
try {
Thread.sleep(2000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
or
synchronized (this) {
try {
wait(2000);
} catch (Exception e) {}
}
Let's set the ground expectation about what battery resources are used for a REST grab.
For these two reasons, there's a lot of other suggestions to handle your implementation.
Firstly, It's recommended to avoid doing polling in favor of Google Cloud Messaging . This allows the server to push information to the client ONLY when updates occur. This will cut down on your battery cost signifncantly.
Secondly, if you can't use GCM (for example, you down control the server), then you need try and optimize your fetches to occur at better intervals.
I'd recommend using GCMNetworkManager , which does all this heavy lifting for you. It'll let you set intervals, wait for the radio to be active, and even handle exponential back-off.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.