determine 3G/WIFI radio state machine current state in Android device - android

my application receives constantly location updates and activity recognition updates, and sending in one batch once in a while all the collected activity and location records to the server.
I know that every time I perform network operations - the radio state of the WIFI or mobile (depends to what is the current active connection) is going to active state, and stays for a while in standby - what can affect dramatically the battery usage when perform frequent network requests, so I'm scheduling alarm to perform the syncing with the server to be execute only once in 2 hours, or when the user explicitly using my application.
from the other hand, we would like to sync the collected data with the server in much shorter intervals if possible.
I was thinking that if I could know when the radio state become active from any reason (e.g when another application perform network operation) - it would be a good chance to perform my syncing, to take advantage the fact that the radio is anyway opened or in stand-by and consuming more power.
my questions:
is it possible to detect this radio state as I desribed?
if yes, then how? and do you think it's a good idea doing so?
I was expecting that the new JobScheduler introduced in android 5.0 will support scheduling jobs when network radio is active, but it does not seems to be the case according to the API. I believe that it will batch all jobs that requires network at the same time, but it will be good only in ideal world when all the applications on the device will use it wisely.

The short answer is no, you currently cannot determine the current state of the network adapter.
Android does not allow you to go that deep into the system. However, you could estimate the state on your own when watching the values in these four files:
/sys/devices/virtual/net/<InterfaceName>/statistics/tx_packets
/sys/devices/virtual/net/<InterfaceName>/statistics/rx_packets
/sys/devices/virtual/net/<InterfaceName>/statistics/tx_bytes
/sys/devices/virtual/net/<InterfaceName>/statistics/rx_bytes
You could read the current traffic of these files and map it to the appropriate state model of the used network adapter. However, the model varies heavily in Wifi, UMTS, LTE, etc. In this whitepaper of the PowerTutor developers (page 4), you can see the state-machine for Wifi and 3G with the transition conditions and timings (they have been found empirically).
In most cases, it's best to stick with the network usage tips provided by the Android developer pages. To be honest, I remember reading something about a network timer, too, but can't find the source anymore.
Edit:
I found the missing source: Project Volta has been introduced with Android 5.0, offering you additional battery features.

I was curious about this same thing, and I finally found an answer here:
http://android.xsoftlab.net/training/efficient-downloads/connectivity_patterns.html
The idea is to use ConnectivityManager like this:
connectivityManager.addDefaultNetworkActiveListener(new OnNetworkActiveListener() {
#Override
public void onNetworkActive() {
// PREFETCH HERE
}
});
I have yet to try it however.

Related

Android Wear 2.0 Architecture issues for realtime complications

I'm developing a set of complications that I would like have regardless of the other installed apps and watch faces. Yes, at some point I am reinventing the wheel, but at the same time I am using this as a learning project. This will also ensure that I always have all the complications I use, available and that they all have the same format and style, instead of relying on 3rd party apps to provide them separately.
The set will have complications for Heart rate, gps coordinates, hours, minutes, seconds, dd/MM date, dd/MM/yy date, battery, etc.
When I started programing all this I found several problematic pieces (most likely because this is the first time I develop complications, or an app for android wear for that matter) and hence this question.
Note that some of this behavior might be specific to the Huawei Watch 2 LTE.
1) Upgrade interval push / pull.
I understand complications as data providers, whose only responsibility is to provide the data to whatever watch face is calling them. This means that we are not certain (and we rely on the watch face developer) to know about the complication and request updates accordingly. This turns some complications completely useless if not updated in time (for example display the Seconds). Could also leave to complications displaying old data (for example old GPS coordinates, old heart rate bpm).
So ok, I decided to implement ProviderUpdateRequester with the AlarmManager to push data to the watch face. The problem again, is with complications that should happen faster, like seconds, as Android will block pending intents if they are schedule too often. So in order to get around that, I decided to use Android handlers within the same service instance, which turn out to be not a good idea because of the next topic.
2) Complication lifecycle
By debugging, I found out that the instance of the ComplicationProviderService object that is executing onComplicationActivated, onComplicationUpdate, onComplicationDeactivated can be different. This means that this is not a sticky service (single instance) that will be always running, but every update creates a new instance of the service. This is problematic because of heavy initialization complications: for example GPS, or Heart Rate monitor that need to listen for new values and it might take a while to retrieve the first value. And also, for those complications that can't rely on AlarmManager, and/or need to keep some sort of state between updates executions.
3) Display aware service
To get around the previous point , let's say you have static variables on your complication service , which are initialized onComplicationActivated and disabled at onComplicationDeactivated. For example, this could be getting a reference for the LocationProvider and starting listening for location updates. This will ensure that each invocation to onComplicationUpdate will not have to perform the heavy/cold initialization and will have access to the most up-to-date data.
However, this also means that your logic will executed regardless if onComplicationUpdate is called or not.
When in ambient mode (or screen off) the watch face can decide not to update the complication by not calling onComplicationUpdate, but it's not aware of our static logic, nor the ComplicationProviderService has a callback invocation for when the screen goes into ambient mode or turns on/off. This is a problem, because in our example, if the screen is off, we are still going to be listening for GPS coordinates, and most likely draining the battery.
Sure, we can deal with this by using a combination of BroadcastReceiver (Intent.ACTION_SCREEN_ON/OFF) and DisplayManager.DisplayListener, but then again, not sure if i'm taking the correct path here, because this will mean that we are now creating services that need to be statically aware of the state of the display.
4) Detect screen on/off
The BroadcastReceiver for Intent.ACTION_SCREEN_ON/OFF works as expected when ambient mode is disabled, but it doesn't it's enabled. When ambient mode is enabled, Intent.ACTION_SCREEN_OFF is dispatched when going into ambient mode, but Intent.ACTION_SCREEN_ON is not dispatched when coming out of ambient mode. While a bit more complex, this can be accomplished by using DisplayManager.DisplayListener to get updates on the onDisplayChanged callback.
TL;RD
1) How do you ensure watch faces display your complications in a timely manner to always have correct and most up-to-date information?
2) How do you deal heavy/cold initialization of a ComplicationProviderService if everytime onComplicationUpdate is called the service instance is different?
3) Is making a long running service display-aware something crazy to do?
4) Technically the screen is still on when in ambient mode, so why is Intent.ACTION_SCREEN_OFF being broadcasted? Why isn't Intent.ACTION_SCREEN_ON/OFF symetrical when ambient mode is enabled?
5) Maybe complications shouldn't be use for exposing realtime information?
Thanks a lot
A couple of things to unpack:
Complications are not meant to be updated frequently (think minutes, not seconds) - this is to preserve battery.
ProviderUpdateRequester is designed more for (on average infrequent) irregular updates like messages coming through a chat app.
Time dependent complications - there are not an "update" as such but Wear provide ways for developers to count up / down from certain time and for displaying date related field (world clock, day of the month) without the provider sending the system updates all the time. For this last one, please refer to docs for ComplicationText.TimeDifferenceBuilder
and ComplicationText.TimeFormatBuilder.
For your use case, a more appropriate thing maybe to consider an always-on app. User uses it for a certain time period for a specific purpose so they explicitly agree to use to use more battery to track things like GPS or heart rate. For example, a lot of running apps on Wear do this.
I hope this helps.

Sending data from Android device to server in the background with minimal user impact

I have an app that generates data that needs to be sent to my server eventually (several hours of delay are no problem at all). I would like to do this with minimal impact to the user, which means to me:
Minimal battery use
No extra permissions, especially not "sketchy" ones
No other strange changes to the system (see example later)
So far I've found three approaches, that all have some serious problems:
Using a SyncAdapter triggered by a network message:
Technically, this sounded like the perfect answer to the problem: Have the system call a service in my app whenever it's doing something on the network anyways. That way, the network is guaranteed to be available, there's barely any extra battery use, since the radio is already on, and the whole thing happens in the background...
And then I tried actually implementing it...
Unfortunately, this approach requires some weird modifications to the system: My app needs to create a new dummy account for the sync-process, even if my app doesn't otherwise use any accounts. And unfortunately, this account cannot be hidden from the user, so now my app is listed when the user clicks "Add Account" in the System Settings, but inside the app, there is no indication of user accounts anywhere... Also, I need to request all sorts of strange permissions, like "Create accounts and set passwords", "Toggle sync on and off", and "Read sync settings". Why would an app that doesn't even provide me with a user account require a permission to set passwords on my device??? Not cool... Delete!!!
Using a BroadcastReceiver and checking for connectivity when it fires:
This requires permission to "view network connections" and possibly even "view information about Wi-Fi networking, such as whether Wi-Fi is enabled and names of connected Wi-Fi devices" ... Why would this app care about my wi-fi or network neighborhood? Creepy... Not getting installed on my device...
The nice thing about this approach is that a network connectivity change likely only happens while the radios are turned on (at least a change to the "available" state). So, if I use this event to trigger an upload (attempt), the battery-impact will be minimal as I won't cause the radio to turn on just for the upload. Unfortunately, this event will probably not be called very often. And to make matters worse, from the docs it sounds like the BroadcastReceiver will only be called while my app is in the resumed-state. So, I won't even be able to make use of events while my app is paused... I.e. using these broadcast events will only be slightly better than option 3:
Just blindly initiating the upload at regular intervals and, if it fails, retrying it again later:
This approach doesn't require any strange permissions and doesn't mess with any system settings. But, clearly, it is the worst I can do for battery use. So, while it's workable, I'd rather find a smarter alternative...
Is there a way to fix the issues of one of the first two approaches? The optimal solution would be a SyncAdapter without a dummy user-account, or, at least, with a hidden one, or one that already exists in the system... But many hours of searching didn't yield any usable answers...
Or is there another better way altogether?
#CommonsWare pointed out two further approaches:
Using JobScheduler:
This allows scheduling jobs for future execution that depend on certain network connectivity or even a certain charging status of the device. It says that it tries to batch job executions for all applications on the system, which may save battery by avoiding additional radio activation, if other apps also have jobs executing that access the network. But if my app is the only one needing to do a network request, I don't think the JobScheduler provides quite the same amount of battery-saving as a network-tickle-driven SyncAdapter would. This is just a guess based on my current understanding, though.
The big issue with using the JobScheduler is that it requires API level 21, i.e. Android 5.0+. For some apps, this might be acceptable, but for me it's not...
Using Google Play Services' Cloud Messenger API, specifically GcmNetworkManager:
This seems to provide pretty much identically the same functionality (except for controlling the retry-backoff-strategy) that the JobScheduler does, except it is available on all devices that have Google Play Services v7.5 or higher installed. Google Play Services is available for devices as far back as Android 2.3, but v7.5 was only released end of May 2015. So, while v7.5 is also available for Android 2.3, it is not guaranteed that it is installed.
To use it, the (supposedly very lightweight) Google Play Services API library needs to be added to the app, which provides the method GoogleApiAvailability.isGooglePlayServicesAvailable(...) that can check if Google Play Services is indeed installed and updated to the version required by the API library. To maximize the chances that this is the case, the API library v7.5 can be added to the app (see here and here for how to get it). If the check fails due to a user-resolvable problem, the library even provides the required dialog to prompt the user to fix the issue (e.g. run an update, ...).
The major advantage of this approach is that it does not require any extra permissions for the app and it doesn't rely on any other changes to the system (mock user accounts, ...). So, it is entirely transparent to the user.
I also found one additional approach, somewhat related to point 3 above:
Using AlarmManager.setInexactRepeating(...):
The AlarmManager also tries to batch callbacks together, just like the JobScheduler and GcmNetworkManager do. In fact, looking at LogCat that sometimes reads "AlarmManager: Checking for alarms... com.google.android.gms", it seems that GCM, and probably also JobScheduler, use the AlarmManager to trigger their execution. The features missing from the AlarmManager are: Suppressing a callback based on network connectivity or battery charging status, and automatic retries of failed executions with a back-off schedule. Technically, one can easily add these features, but some of them, like checking for network connectivity, might require additional permissions.The major advantage of this approach is: It's available on almost all devices (starting API level 3).
Currently I have the GcmNetworkManager approach implemented (point 5) and it works as expected.
But I'm actually considering moving to AlarmManager.setInexactRepeating(...) (point 6) to maximize compatibility. Checking for the device charging state seems to be possible without extra permissions and rather than checking for network connectivity, I can just fire off the http request and check whether it failed... The only feature I would be missing is determining whether the user is on a metered connection or not. And, of course, it will be a bit of work to implement retries, back-offs, ...
Update:
It seems like JobScheduler actually does detect existing network activity (see this JobScheduler introduction), which might make it superior to just using the AlarmManager, and pretty much as good or better than SyncAdapters... The GCM documentation also claims callback optimization based on current network activity (not just availability)... So, I guess the optimal solution would be to use the JobScheduler where available and fall back to GCM where it's not and to the AlarmManager where GCM isn't available either... Yuck...

Does coarse location use less battery than geofences on Android?

I'm trying to know when your device leaves your home, but I don't need fine GPS location nor high update rate (i.e. it's fine if I know the user is out only 10 minutes after he left his home and he's already 100 meters away).
Which of the two solutions should use less battery (both should use already less battery than plain GPS location listener)?
Receiving Location Updates | Android Developers with PRIORITY_BALANCED_POWER_ACCURACY
Creating and Monitoring Geofences | Android Developers
The first is for sure using a more battery saving solution and I can control the frequency to be low.
The second is a higher level API which does just what I want but I've no idea what it does and it looks like it'll use fine GPS location constantly while the user is within the geofence (remember I want to reduce battery usage).
Anyone has some insight on this regarding mostly battery usage?
The answer here might be a combination of things. The Location and battery Drain video explains more about how the GPS & Location chips burn up battery in your device. (Battery Drain and Networking will detail how the Radio chips work.)
Basically, using a FusedLocationProvider will allow you to scale back accuracy vs. power drain. Basically less-resolution results in less battery drain.
Knowing that, I'd suggest a set of low-power checks as early-warnings before moving to the higher-power checks:
Use ConnectivityManager to determine if the mobile device is on the CellularNetwork or not. If they are, there's a good chance they've moved outside of the wifi boundries.
Check if the WiFi they are connected to is the common home WiFi (so you don't mistake the coffeeshop wifi as home).
Use a back-off system on your checks. If the user is home, chances are, they will be there for a while; so scale back how often you check position.
If the user is on Cell network, use a Course Location to determine if you're within 100ft of your known home location.
Use a Fine location check to resolve issues / corner cases with the Course Location check.
When all else fails, do a Geo Fencing check; but then turn it off as soon as you've resolved the issues.
Basically, you want the least-power draining options to run the most often, and only use the most power-draining when you're resolving discrepancies in position.
There are a few hints in the documentation that Google wants you to use the Geofencing (or the new Awareness API) for your use case.
The first method need to be triggered from a LocationRequest, and from
https://developers.google.com/android/reference/com/google/android/gms/location/LocationRequest
Activities should strongly consider removing all location request when entering the background (for example at onPause()), or at least swap the request to a larger interval and lower quality.
This shows that this API is designed to be used only when your application is active, hence the "Request" term.
Google soon realized that a lot of apps (including their own Google Now) are requesting for location in the background, and they want to improve it in such a way that the requests can be pooled and shared, hence they created Geofencing and eventually Awareness API.
From the Fence API document,
https://developers.google.com/awareness/overview#fences_and_snapshots
Fence API lets your app react to the user's current situation, and provides notification when a combination of context conditions are met. For example, "tell me whenever the user is walking and their headphones are plugged in". Once a fence is registered, the Fence API can send callbacks to your app even when it's not running.
So, in your use case, if your app is not running, you should be using the second method.

execute periodic network requests in batch

I would like to know about the behavior of android in case of periodic network requests. As of Android Kitkat documentation "Android works with the device hardware to collect and deliver sensor events efficiently in batches, rather than individually as they are detected. This lets the device's application processor remain in a low-power idle state until batches are delivered". This functionality was introduced in android 4.4.
AlarmManager redefined in Kitkat "To improve power efficiency, Android now batches together alarms from all apps that occur at reasonably similar times so the system wakes the device once instead of several times to handle each alarm".
So my question is that, is there any way to do the same in case of network calls or any API available which provides the same functionality.
I searched and found that, there is no simple API available for batch network calls but there is a way to achieve the goal is to use the Google's recommendations about regular updates.
As per documentation "When scheduling updates, use inexact repeating alarms that allow the system to "phase shift" the exact moment each alarm triggers".
Official Documentation

Android GPS and battery usage

I have 2 android applications A and B, and both of them are reading gps values based on different parameters. Considering both the apps are running on the device, which of the folllowing approaches would be better?
Both A and B are to be different apps, each one with a component to read from GPS.
To develop a third application with a remote service component to transmit GPS data to both A and B
Would battery usage be minimized by going for the second approach or will the GPS component read once and serve all processes, as in the OS?
Please help
There is a very good explanation given in the Android Developers Website about Location Strategies. I would suggest you to take a look at the code examples on the page.
In both of your approaches i believe second approach is quite better because Turning on/off GPS is a quite expensive operation in terms of battery usage.
GPS’s battery draining behavior is most noticeable during the initial acquisition of the satellite’s navigation message. Acquiring each satellite takes 12 to 30 seconds, but if the full almanac is needed, this can take up to 12 minutes. During all of this, your phone is unable to enter a deep sleep. A-GPS (Assisted GPS) partially solves this, by sending the navigational message to your mobile device over your cellular data network or even Wi-Fi. As the bandwidth of either of these greatly dwarves the 50bps of the GPS satellites, the time spent powering the GPS antenna or avoiding deep sleep is greatly reduced.
Referred from this.
I think the most battery-efficient way would be to poll the GPS location with app A normally, and in app B, use LocationRequests and use setPriority() with PRIORITY_NO_POWER. As mentioned in the docs, PRIORITY_NO_POWER will make app B get updates only when another app gets GPS updates (in this case, app A!!). I haven't tried it, but it should work. It definitely saves you the hassle of an extra app :)
Some more info on Google Play Location Services here and here.
is it the same as OS gPS component will run once to serve all
One GPS serves all.
There is no half GPS saving half the power.
But there are other location providers like cell tower and Wifi locationing which uses less power.
But if you need GPS it is absolutley no difference how many apps uses the GPS service.
If GPS is enabled it uses full power.
For the sake of compatibility and function I would suggest having a third process or program which reads and outputs GPS data, as multiple processes polling data from GPS is less efficient.
It would also be faster to have those two apps read the output of a single GPS tracking app and not needing individual components in each app to do so.
For the sake of power the GPS will use the same level of power regardless, though if it's polled more often due to two applications using it then it may use more - though the amount is likely to be minimal unless there are constant requests for location.
Though this may not be the question it would be most power efficient to have the third application poll GPS at specific intervals and the applications may read from its output rather than search location every time.
Second approach seems to be more appropriate but not sure about battery drainage.It depends upon how you implement it.
Also I would suggest try to use passive providers.Refer following link help it works :)
http://fypandroid.wordpress.com/2011/04/11/298/

Categories

Resources