Can not run Wifi and Bluetooth scans in background with Flutter - android

I am working on a part of an indoor localization project. I need my Flutter application scan and get Mac addresses and RSSI values of Wifi and Bluetooth devices. I am using flutter_blue for bluetooth scans and wifi_scan for Wifi scans. The application works well while in the foreground but scans are failing when the application is in background.
What I have tried so far:
Tried to change Bluetooth scan mode from ScanMode.lowLatency to ScanMode.lowPower and ScanMode.opportunistic for the startScan() method for flutter_blue.
flutter_background. I managed to do some tasks in background but wifi and bluetooth did not work.
flutter_background_service the same situation
flutter_foreground_plugin the same situation
flutter_foreground_task the same situation
workmanager did not try it because it says it can trigger the bg operation per every 15 minutes but I am scanning per every 6 seconds.
Is there any way to achieve this? Aren't there any package with the option backgroundMode: true? I don't know the natives. Don't know Kotlin too.

According to the Android Developer documentation, ScanMode.lowPower is the only possible mode for background scanning. You also need to request location access for the background (documentation here and here).
Consider switching to Flutter Blue Plus instead of Flutter Blue; Flutter Blue Plus is the currently-maintained version. This pull request on GitHub shows that Flutter Blue cannot run in the background. The pull request has never been merged.

After a lot of things have been tried, I just tried to get GPS location too.
Used this package: location
And execute location.enableBackgroundMode(enable: true) as it is stated in readme, then my wifi and bluetooth scans starts working in background too.
It's Ridicoulus

Related

Scan Bluetooth devices in android studio

I try to write a code from documentation but every time it asks for self-check permission and I did not get any device name
Help me to write a code to scan devices in the area
GitHub repositor link for my application
https://github.com/sachinraj0093/BluetoothAttendance/blob/master/app/src/main/java/com/example/bluetoothattendenceapplication/MainActivity.java
If your device running on Android 11 or lower, you need to check the Location is turned on. And in your code, you lack of calling discovery in case !mbluetoothAdapter.isDiscovering().
You can check returned value when call BluetoothAdapter.startDiscovery() to examine the status for start discovery action.

How to know if my App is connected to a device using BLE in Flutter?.. when app is the beacon

So my android app is behaving as a beacon, means, it will be advertising and other BLE devices will be connecting to it. Well, this is how our project is working so please don't raise questions on this as why am i using my app as a beacon and not as a scanner. Anyways, It behaves as a beacon and starts advertising and now I want to know that if a device connected to it. I cant find a way how to do this.
Of course, I am using this flutter package. beacon_broadcast 0.3.0
This is my code.
void startAdvertising() {
BeaconBroadcast beaconBroadcast = BeaconBroadcast();
beaconBroadcast
.setUUID(advertisingUUID)
.setMajorId(1)
.setMinorId(100)
.start();
}
First, Flutter is just a UI toolkit and has no support for other system APIs such as Bluetooth.
You should therefore look what the official Android APIs offer in the first place. Usually when using BluetoothLeAdvertiser for advertising, one often also adds an instance of BluetoothGattServer in order to handle connections. If you have created a BluetoothGattServer using openGattServer, you will get a onConnectionStateChange callback whenever a device connects or disconnects. So that answers your question how an Android app can get notified when a device connects. You probably also want to use the same API to add a GATT service so that the other device can communicate with your app. Other alternatives is to use the GATT client API if it's the other device that has a GATT server, or you might want to use the L2CAP CoC API.
Note that if Bluetooth is turned off/disabled/restarted, your BluetoothGattServer object will automatically die and you need to recreate it. To get notified when this happens, use a state change intent receiver for BluetoothAdapter.ACTION_STATE_CHANGED as explained in this example https://stackoverflow.com/a/9694138/556495 to recreate your BluetoothGattServer (and advertiser) when state is changed to STATE_ON.
Now, since you want to use Flutter but Flutter uses Dart, you cannot directly consume the Android APIs. Instead you need to write a bridge/plugin, to bridge your Dart code and Java code. See https://docs.flutter.dev/development/platform-integration/platform-channels for a tutorial how to do this. If you're lucky, someone else might have already created such a package that does exactly what you want. Unfortunately, the beacon_broadcast package you found, only implements BluetoothLeAdvertiser and not BluetoothGattServer, as can be seen by the source code here: https://github.com/pszklarska/beacon_broadcast/tree/master/android/src/main/kotlin/pl/pszklarska/beaconbroadcast.

Android Beacon Library - extending BluetoothMedic for unconditional resets?

I have an Asus P00A tablet (Android 7.0, API24) on which the BLE stops after some hours. (This affects any BLE app, not just my app using Android Beacon Library). Apps start working again if I manually switch off BLE then switch it back on.
The BluetoothMedic auto-fix system did not work for my tablet. It runs every 15 minutes but does not find a fault and so does not "power cycle" the Bluetooth. However, I hacked the BluetoothMedic class, adding this:
public void cycleBluetooth(Context context) {...}
and attached this to a button. I find this will restore BLE functionality. So I wondered what would happen if I unconditionally reset the BLE every 15 minutes. I added:
public static final int ALWAYS_RESET = 4;
and then call medic.enablePeriodicTests(context, BluetoothMedic.ALWAYS_RESET);
and add code inside BluetoothTestJob.onStartJob() which then calls BluetoothMedic.cycleBluetooth(). This behaves as expected and so far my app has run perfectly for 18 hours.
I am interested in any advice, such as:
1 Are there any tests other than the two in BluetoothMedic that I can run to detect that my tablet's Bluetooth has stopped? (I am happy to experiment).
2 Any comments on the hack I describe above? Should it be OK to unconditionally reset the Bluetooth every 15 minutes?
3 If the Bluetooth is reset ("power cycled") then is the rest of the Android Bluetooth Library OK with this? That is, will it carry on with monitoring and ranging that has been previously set up, or does the application code need to set take any action to get things going again? Note that this would apply to resets by the existing enablePowerCycleOnFailures() code as well as my ALWAYS_RESET hack above. (Maybe there are some crashes that could happen if the power cycling came at the wrong time?).
4 Could I suggest adding a callback so the application can learn if the Bluetooth has been cycled? Perhaps as a parameter to enablePowerCycleOnFailures()
5 I understand that background activities can be stopped by the OS, especially with Android 8. Would this also affect the regular 15 minute tests set up by enablePeriodicTests()?
The Android Beacon LIbrary's BluetoothMedic, as currently built, relies on the operating system's error code returned by a scan failure (or an advertising failure) to decide if the bluetooth stack is in a bad state warranting a power cycle.
For scans, if the onScanFailed callback is called with an error code of SCAN_FAILED_APPLICATION_REGISTRATION_FAILED which has the value of 2, the module considers it worthy of a power cycle..
For advertisements, if the onStartFailed callback is called with an error code of ADVERTISE_FAILED_INTERNAL_ERROR which has a value of 4, the module considers it worth of a power cycle..
These values were determined via experimentation, witnessing that on some devices, once an error callback is called with these values, bluetooth on the device would not work again without turning it off and back on. You can see the discussion of this in this thread.
You may want to see if there are other error codes on the Asus P00A that indicate a problem worthy of cycling bluetooth. To do this, wait for a failure, and see if attempts to start scanning call the onScanFailed callback with a distinct error code. If such error codes exist, this would be a better solution than cycling power to bluetooth regularly, as cycling power to bluetooth does break BLE GATT connections and the operation of bluetooth classic functions like speakers. The Android Beacon Library itself recovers from these power cycles just fine, although it will obviously not detect beacons until bluetooth is back on.
Because the BluetoothMedic uses the Android Job Scheduler for periodic tests, it is not affected by background limitations on Android 8+.
If you are interested in augmenting these functions in the library, please feel free to open an issue in the Github repo, and issue a Pull Request if you have code to share.

Cannot set temperature interval on sensortag

I'm creating an android application that interfaces with the texas instruments sensortag. One of the things the app needs to do is be able to change the frequency in which the temperature is reported to the app. I am able to change it through the official TI app which is great, but I cannot seem to get it working in my app.
When viewing the official app (iOS, can't run the android one?), it shows the temperature GATT service, which contains 3 characteristics. When I inspect the characteristics discovered by my app however, it only seems to find two - the data, and the notifications. Not the interval. I have attempted to construct this characteristic myself and write it however it doesn't do anything - no error, no success, just nothing.
The steps I've taken are essentially:
bluetoothGatt.discoverServices();
...
services = bluetoothGatt.getServices();
...
BluetoothGattService service = bluetoothGatt.getService(serviceUUID);
System.out.println("Characteristic = " + service.getCharacteristic(SensorTagGatt.UUID_IRT_PERI));
The output yields null. Is there something obvious I'm missing or that I should be doing that I might not be?
EDIT:
I've installed another app onto the phone written by another developer, and using this to inspect the services and characteristics available shows that it too is unable to find it, so I'm assuming there is something wrong with the android service discovery? The official iOS app is working as expected, and showing all characteristics. Unfortunately, the official android app seems to be incompatible with the version 1.5 firmware and crashes when trying to connect but I assume it too will fail to find the characteristic.
Has anyone else run into this issue and if so been able to get around it?

Make Bluetooth on Android 2.1 discoverable indefinitely

I'm working on a research project which involves Bluetooth and the Android OS. I need to make Bluetooth discoverable indefinitely in order for the project to continue.
The Problem:
Android limits discoverability to 300 seconds.
I cannot ask the user every 300 seconds to turn discoverability back on as my application is designed to run in the background without disturbing the user.
As far as I am aware, there is no way to increase the time though Android's GUI. Some sources have called this a safety feature, others have called this a bug. There may be a bit of truth in both...
What I'm Trying / Have Tried:
I'm trying to edit a stable release of cyanogenmod to turn the discoverability timer off (it's possible; there's a configuration file that needs to have a single number changed). This isn't working because I'm having verification problems with the resulting package.
During the past week, I downloaded the cyanogenmod source code, changed a relevant class in the hope that it would make Bluetooth discoverable indefinitely, and tried to recompile. This did not work because (a) the repo is frequently changed, leading to an unstable code base which fails to compile (OR, it could be that I'm using it incorrectly; just because it looked like it was the code's fault in many instances doesn't mean I should blame it for all the problems I encountered!) and (b) the repo decides to periodically "ignore" me (but not always, as I have gotten the code base before!), replying to my synchronization/connection attempts with:
fatal: The remote end hung up unexpectedly
As you might imagine, the above two issues are problematic and very frustrating to deal with.
More Info:
I'm running Android 2.1 via cyanogenmod (v5 I believe). This means the phone is also rooted.
I have a developer phone, which means that the bootloader is unlocked.
My phone is an HTC Magic (32B).
The Big Question:
How can I make Bluetooth indefinitely discoverable on Android?
See the following link:
http://developer.android.com/guide/topics/wireless/bluetooth.html#ConnectingDevices
Specifically, the last sentence in the paragraph below:
Enabling discoverability
If you would like to make the local device discoverable to other devices, call startActivityForResult(Intent, int) with the ACTION_REQUEST_DISCOVERABLE action Intent. This will issue a request to enable discoverable mode through the system settings (without stopping your application). By default, the device will become discoverable for 120 seconds. You can define a different duration by adding the EXTRA_DISCOVERABLE_DURATION Intent extra. The maximum duration an app can set is 3600 seconds, and a value of 0 means the device is always discoverable.
So, this should work:
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
startActivity(discoverableIntent);
If you check out the BluetoothAdapter class
you will find the hidden method:
public void setDiscoverableTimeout(int timeout)
Now you only have to find out how to use it. You have to do a method invocation to do so.

Categories

Resources