The very weird way of checking if Bluetooth or Location is enabled
As I am in constant development of new features for my NFC Toolkit, I came to the point where I needed to detect if Bluetooth and Location is enabled or not.
I searched about an hour across the internet, searched all well known WPDev sites as well as the MSDN Windows Phone documentation.
The solution is a very weird one.
As I change the opacitiy of an Image depending on the stauts (on/off), I created the following async Task to check:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private async Task GetBluetoothState()
{
PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
try
{
var peers = await PeerFinder.FindAllPeersAsync();
Dispatcher.BeginInvoke(() =>
{
BluetoothTileImage.Opacity = 1;
});
}
catch (Exception ex)
{
if ((uint)ex.HResult == 0x8007048F)
{
Dispatcher.BeginInvoke(() =>
{
BluetoothTileImage.Opacity = 0.5;
});
}
}
}
As you can see above, we are searching for already paired devices with the Proximity API of Windows Phone. If we don’t have any of our already paired devices reachable, and we don’t throw an exception with the HResult of “0x8007048F”, Bluetooth is on. If the exception is raised, Bluetooth is off.
In a very similar way we need to check if the location setting is on:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
private async Task GetLocationServicesState()
{
Geolocator geolocator = new Geolocator();
try
{
Geoposition geoposition = await geolocator.GetGeopositionAsync(
maximumAge: TimeSpan.FromMinutes(5),
timeout: TimeSpan.FromSeconds(10)
);
Dispatcher.BeginInvoke(() =>
{
LocationStatusTileImage.Opacity = 1;
});
}
catch (Exception ex)
{
if ((uint)ex.HResult == 0x80004004)
{
Dispatcher.BeginInvoke(() =>
{
LocationStatusTileImage.Opacity = 0.5;
});
}
else
{
//tbd.
}
}
}
For the location services, the HResult is “0x80004004”. We are trying to get the actual GeoLocation, and if the exception is thrown, location setting is off.
On Twitter, I got for the later one also another suggestion to detect if the location settings is enabled or not, by Kunal Chowdhury (=>follow him!):
geoLocator.LocationStatus == PositionStatus.Disabled;
This would work technically, but PositionStatus has 6 enumarations. Also, as stated here in the Nokia Developer Wiki, this can be a battery intese call (depends on the implementation). I leave it to you which one you want to use.
Back to the header of this post. Catching an exception to determine the Status of wireless connections just seems wrong to me. I know this is a working “solution” and we can use that. But it could have been better implemented (for example like the networking API).
I hope this post is helpful for some of you.
Until then, happy coding!
Comments powered by Disqus.