Android Bluetooth LE disabling notification callback drain battery? - java

I'm developing an application that connects to a Bluetooth Low Energy Device. The architecture of the program requires it to collect data from this device in bursts. Example: Collect data for 30 seconds once every 3 minutes.
It is very important for this to be battery efficient.
For this device I have subscribed to notifications from a BluetoothGattCharacteristic. Unfortunately read permission is not given on this characteristic, so notifications must be used.
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
and
mBluetoothGatt.setCharacteristicNotification(characteristic, true);
My first idea is to simply set
mBluetoothGatt.setCharacteristicNotification(characteristic, false);
when not scanning for data. Will this still consume lots of battery life? I assume the callbacks are still listening. Would I be required to change the descriptor back to its non-notification state?
Another idea would be to connect only when reading data from sensors, and disconnect when done. This would mean reconnecting ~20 times an hour.

Suggestion
I will suggest reading characteristic values instead of setting them for notification. This way you will only require to communicate when you need data from BLE Device.
Questions
1) How frequently do you think Characteristic data will change at BLE device side.
2) Are you worried about battery drain at BLE Device side or of phone Battery??

Related

Running multiple asyntasks

I have a task to fetch data from server at start if application. For purpose i am calling an api by asynctask for notification codes and parse data. The data can go upto 60000 notification codes.
For each notification code i have to call different apis to get data. After performing operation i need to again call an acknowledge api to tell server notification has been acknowledged. So next time when getting notification code it dont repeat.
So in the case i have to call approximately 60000 asynctask for operation and 60000 for acknowledgement. Do each operation for different api urls and then Acknowledge each operation for different url simultaneously
My app is working when notifications are below 1000 but for more than that notification it stucks.
Please anyone can guide what's the best way to implement this.

Is there any alternative for PeriodicWorkManager, if I would like to run a background work more frequently than 15 minutes?

The PeriodicTimeRequest has a minimum periodic time of 15 minutes. But I see, that for example Google Maps location sharing can update more frequently than that, and facebook messenger can also receive messages almost instantly.
I would like to send a notification to the user, when it got a new message. My application has to work on local network, so Firebase is not an option. I have to send a json request to the server, and if there is a new message, I show a notification to the user.
Regarding FCM:
FCM, which is available in all devices with Google Play takes the weight of subscribing to and receiving push events, under all the resource constraints Android has been ever introducing.
It's tightly coupled with the OS and is unified (one entity, one persistent connection for all apps in your device), which is why it works :)
Regarding Frequency of your Work:
Given your requirement of more frequent pings to the server, you'd need to have a service which runs all the time, i.e. A Foreground Service.
It is resource consuming though, so good luck convincing the user with a good reason why it should stay alive all the time.
I think you've managed to make the client-server interaction possible, since identifying a server in a local network is a huge task in itself.
use this in your service.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
CountDownTimer timer = new CountDownTimer(15 * 60 * 1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
// execute your task here, every sec
//if you want increase the count down interval from 1000 to what you want
}
#Override
public void onFinish() {
this.start();
// it will start again.
}
};
timer.start();
return START_STICKY;
}
I am afraid it is not going to be possible without using a set of workarounds. Which means you might not get a consistent behavior.
#Arvind has done a very good job explaining the benefits of a Firebase Service and it is the recommended approach for achieving such task.
First I'd like to point out that such restrictions on the WorkManager exist because Android has been suffering (between other things) of developers trying to abuse some mechanisms to get their software working and at the end of the day, the battery of the users had been suffering from such abuses and since Android 6 Google has started trying to address these issues. There's a good read for you over here about Doze mode and how to work with it
I am pointing this stuff out because I've been trying to build a chat service that wouldn't rely on Firebase and I really don't want you to waste as much time as me banging your head against a wall. There are things that you simply can't fight. That means that if the device enters in a "deep-sleep" mode sometimes you can only accept it.
My approach
Please
keep in mind the user interests and the life of their batteries and try to be as smooth as you can with their devices and this is just a workaround over the restrictions that have been imposed upon us. And that I discourage this approach due to the amount of work that it takes to pull off and for how misused it can be.
My solution
Essentially, to get notified (ie getting your code running) in an Android App you're going to be wanting to receive system events or Broadcasts. This is where you set up a BroadcastReceiver and you get Intents delivered to it and you can act upon them accordingly. BUT YOU HAVE TO BE QUICK BECAUSE YOU HAVE ONLY 10 SECONDS OF RUNTIME BEFORE THE OS KILLS THE PROCESS AGAIN. Ideally you would have a really quick server so you can have very little IO times to ensure you can be within 10 second restriction as frequently as possible.
So essentially you would be using a combination various of services that you would like to be monitoring in order to get notifications (aka Broadcasts) whenever the state of those changes. Here are a few ideas:
WiFi state (which will also be useful to see if you can reach your local server)
Bluetooth Low Energy packets (or Nearby which may solve the entirety of your problem depending on Nearby's capabilities)
WorkManager as you already pointed out.
AlarmManager to schedule a broadcast of intents every so often.
Geofencing (although it involves reading the user's location; you can set really small geofences around the office building and get notified by a Broadacast when users go through that geofence)
So whenever you receive a Broadcast of these sources you would handle such notifications from within the same BroadcastReceiver
From the implementation body of this Broadcast receiver you would poll the local network's server to check whether if your user has new messages or not and lift up a notification. And it's important to keep the amount of work and IO times the app has to do at a minimum since those add up and you've got only 10 seconds.
You can get around the 10 second mark if you launch a ForegroundService. Then, that period of time is going to be extended until a 10 minute mark and you will need a visible notification for the user stating something that you're checking if it's got any new messages.
Keep in mind
Don't stress the user's battery too much. Or Android will penalise your app and you'll end up notified less often or even completely not notified.
Be gentle with the user. If the user has to force-kill your app at some point it will stop receiving any sort of Broadcasts or running any sort of WorkTasks.
This solution can behave differently accross devices. Since the decisions of notifying your app are made by the OS, different OS (redmi, samsung, meizu...) you are likely to not end up with a consistent behavior across all devices
You don't have control over things, the OS does
Within measure, try to time your Broadcasts to your BroadcastReceiver within spans of 3 minutes or so; so you are always receiving a Broadcast below the 15 minute mark.

Does android system blocks FCM notification

I am sending a data notification every 2 min for the device in order to collect data (GPS, Signal strength ...).
The FCM trigger service that sends the collected data to an API
However, The device stops receive FCM notification to starts that app in some cases or even till restart it.
Is there any reason for this and how Can I pass it?
Note: I have Add server up to white list in the firebase console
Generally there are two types of FCM messages we can send to registered devices. First one is data message and the other one is notification message. The default priority of data message is NORMAL where as the notification messages have a HIGH priority. Messages with HIGH priority are considered to be delivered first (That means there is a chance of not receiving data messages in some case). But it is possible to change the priority of data message to HIGH while sending them from server.
https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message
But in my case i had some situations when i was not able to receive FCM messages even after setting priority to HIGH. Thus i opted to use FCM wrapper services like Onesignal to send push notification. It is way better in case of message delivery. Inside it is FCM, but they handled the message delivery problem up to an extent. Take a look at
https://onesignal.com/

Microsoft Band 2 Data stops streaming for accelerometer and gyroscope

I have been developing an Android app to track eating throughout the day. We have not decided on which sensors to use yet, so the app is capable of connecting to all of the sensors from a Service and streaming them for an indefinite amount of time, depending on when the phone decides to clean up the app's resources. What I have noticed during reliability testing is that accelerometer and gyroscope cut out after two to three minutes when they are both streaming at medium or high frequency. I have implemented a timeout thread that checks for the last received accel or gyro data (depending on if they are supposed to be streaming) and re-registers new listeners if they stopped streaming. Is anyone else having this issue and/or does anyone have recommendations for a less battery intensive way of reliable acc/gyro streaming?
To summarize:
Registered accelerometer and gyroscope listeners stop receiving data after 2-3 minutes
This only happens when streaming accel/gyro at the medium and high frequency settings and only when accel and gyro are both streaming
This happens regardless of whether other sensors are streaming or not
No exception is thrown when this happens
Subscription/unsubscription as well as incoming data are all handled on new threads
I have a hacky timeout thread that unregisters and registers new listeners for accel/gyro if they stop streaming
Questions:
Is anyone else running into this issue?
Is there an issue with using new Threads to handle the data that would be causing the listeners to be unregistered (unlikely because other data works implemented this way)?
Is there a better (more battery efficient) way of detecting an event not occurring and responding to that than having a thread check for a timeout?
Thanks in advance!
Four things.
1) The Microsoft Band gyro sensor data on the SDK includes the accelerometer data, so you should never need to subscribe to both at the same time.
2) Subscribing to either over a long time will drastically drain the battery life of whatever band is being connected to and is thus not advised.
3) Streaming requires that a connection to Microsoft Health's BandService remains active. And if that connection is lost, you will no longer get data. (Likely this is what is happening in your case)
4) Microsoft has a cloud API that might be more useful for what you want to do. http://developer.microsoftband.com/cloudAPI
Do you have any other devices connected to your phone via Bluetooth? If so, try disconnecting everything except the Band.
From my experience, having another device paired and communicating with the phone causes the listeners to shut out without notice, often requiring a restart of the app or the phone. My phone was collecting data from a tablet and the sensors at the same time, and I discovered that the sensors would last more than 2-3 minutes if I didn't connect to the tablet at all.
Hope this helps!

Some seconds delay on starting sending Voip with Android.net.rtp

I implemented an Android app that uses Voip by Android.net.rtp library.
It simply gets voice from device microphone and sends it in Voip (to another Android or to a PC receiver).
The problem is that on some devices the voip trasmission start after 2–3 seconds. I don't mean that there is a delay of 2–3 seconds in delivering packets, I mean that the first 2–3 seconds of voice are not sended. After those 2–3 seconds everything works properly.
The strange thing is that it happens only on some android device, and it is not a problem of device performance or Android version. For example it happens on a very old device and in a new one, while it doesn't happen in another very old device and in another new one…
I thought to some Android service/functionality that delays mic capture, but I didn't find out anything at the moment…
In the following, the code I use to send Voip, it is a classical code:
myAudioStream = new AudioStream(myIPAddress);
myAudioStream.setCodec(AudioCodec.PCMU);
myAudioGroup = new AudioGroup();
myAudioManager = (AudioManager) myContext.getSystemService(Context.AUDIO_SERVICE);
myAudioGroup.setMode(RtpStream.MODE_SEND_ONLY);
myAudioStream.join(null);
myAudioStream.setMode(RtpStream.MODE_SEND_ONLY);
myAudioStream.associate(ipAddress_Receiver, port_Receiver);
myAudioStream.join(myAudioGroup);
myAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
myAudioManager.setSpeakerphoneOn(false);
myAudioManager.setMicrophoneMute(false);
Check if you can disable ICE and/or STUN in Android.net.rtp. These are usually responsible for the delay at media setup.
after some debugging I discovered that the AudioManager is introducing the delay in the setMode call:
myAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION))
The strange thing is that it depends from the device. With some devices it can introduce also 2-3 seconds, with other devices no delay is introduced.
See similar answer in:
Is there any significant delay in initializing AudioTrack on Android?
Finally I found out this solution, setting:
myAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
in the costructor of my class, then only once. I invoke the costructor on starting of my App, when I didn't start the voice TX yet.
In this way, when I have to speak I don't have to loose those seconds...
Hope to be usefull for somobedy else.

Categories

Resources