How to detect android watch is worn or not on AW2.0 - wear-os

Android wear 2.0 screen can be automatically locked right after it is taken off
and the heart rate app / watch face would not work when it is not worn.
I am wondering is there any way to get current wear worn state without starting a service to listen to wear activity?
I tried to get the heart rate sensor accuracy, but I don't think it is a good way because I can not always get the right result in this way immediately.
Is there any system or gms API to get a current worn state synchronously?

On watches with an off-body sensor (which lock immediately when not worn), you can check for the existence of the wakeup sensor TYPE_LOW_LATENCY_OFF_BODY_DETECT. This is only a public API in O+, but you can just use the actual value for N MR1 and below.
SensorManager sensorManager =
(SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
boolean hasSensor = sensorManger.getDefaultSensor(34, true /* wakeup */) != null;
On watches without an off-body sensor (which don't lock immediately), your best bet is probably some sort of activity recognition, though there don't seem to be any public off-body activities that can be detected by Google APIs (see here).

Related

MacOS not responding to MPRemoteCommandCenter commands in the background

I am writing an application for my own purposes that aims to get play pause events no matter what is going on in the system. I have gotten this much working
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.togglePlayPauseCommand.isEnabled = true
commandCenter.togglePlayPauseCommand.addTarget { (MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus in
print("Play Pause Command")
return .success
}
commandCenter.nextTrackCommand.isEnabled = true
commandCenter.nextTrackCommand.addTarget { (MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus in
print("NextTrackCommand")
return .success
}
commandCenter.previousTrackCommand.isEnabled = true
commandCenter.previousTrackCommand.addTarget { (MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus in
print("previousTrackCommand")
return .success
}
commandCenter.playCommand.isEnabled = true
commandCenter.playCommand.addTarget { (MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus in
print("playCommand")
return .success
}
MPNowPlayingInfoCenter.default().playbackState = .playing
Most of those methods are there because apparently you will not get any notifications without having nextTrackCommand or previousTrackCommand or playCommand implemented.
Anyways my one issue is that as soon as you open another application that uses audio these event handlers stop getting called and I cant find a way to detect and fix this.
I would normally try doing AVAudioSession things to state this as a background application however that does not seem to work. Any ideas on how I can get playpause events no matter what state the system is in?
I would like to be able to always listen for these events OR get an indication of when someone else has taken control of the audio? Perhaps even be able to re-subscribe to these play pause events.
There's an internal queue in the system which contains all the audio event subscribers. Other applications get on top of it when you start using them.
I would like to be able to always listen for these events
There's no API for that but there's a dirty workaround. If I understand your issue correctly, this snippet:
MPNowPlayingInfoCenter.default().playbackState = .paused
MPNowPlayingInfoCenter.default().playbackState = .playing
must do the trick for you if you run it in a loop somewhere in your application.
Note that this is not 100% reliable because:
If an event is generated before two subsequent playbackState state changes right after you've switched to a different application, it would still be catched by the application in the active window;
If another application is doing the same thing, there would be a constant race condition in the queue, with unpredictable outcome.
References:
Documentation for playbackState is here;
See also a similar question;
See also a bug report for mpv with a similar
issue (a pre-MPRemoteCommandCenter one, but still very valuable)
OR get an indication of when someone else has taken control of the audio
As far as I know there's no public API for this in macOS.

Geolocation.GetLastKnownLocationAsync() sometimes returns null

This is on iOS 12.1.4 on an iPhone 6s. Usually Geolocation.GetLastKnownLocationAsync() works but sometimes it doesn't. It's the exact same code but if I sit here and press my "get latitude and longitude" button over and over eventually Geolocation.GetLastKnownLocationAsync() spits out a null.
Do you know why this happens and how I might handle it? Perhaps put it in a loop that tries ten times, waiting a second between each try?
var location = await Essentials.Geolocation.GetLastKnownLocationAsync(); // works most of the time but sometimes it doesn't work.
This is my proposed work around:
Essentials.Location location = null;
for(var i = 0; i < 10; i++)
{
location = await Essentials.Geolocation.GetLastKnownLocationAsync();
if(location == null)
{
Thread.Sleep(1000);
}
else
{
break;
}
}
First, it is really bad practice to use Thread.Sleep (unless you are not on the main/UI loop) as you are hanging the run loop, if you really need a delay, use await Task.Delay(.... Also CLLocationManager on iOS is running on the main loop and if you are blocking it, the message pump is hung and the location manager manager can not report back to the app.
"Spamming" CLLocationManager.Location (which Essentials is using on iOS) can (and will) result in null returns due to OS rate limiting updates (mainly a battery conservation measure) and if the OS is powering up the GPS radio to update its location, this method will timeout on from the OS, thus report nil back to GetLastKnownLocationAsync and thus you get a return of null.
CLLocationManager.Location on iOS is meant for a quick low-power return from the OS to app as is updated upon app launch, device reboot, etc... not every time you call it.
You can get the last known location of the device by calling the GetLastKnownLocationAsync method. This is often faster then doing a full query, but can be less accurate.
Otherwise you should be using GetLocationAsync in order to do a full GPS power up to obtain an updated accurate location.
To query the current device's location coordinates, the GetLocationAsync can be used. It is best to pass in a full GeolocationRequest and CancellationToken since it may take some time to get the device's location.
Typically I recommend using GetLastKnownLocationAsync as a quick way to get the general area of the user knowing that this might also return null. Then proceed to do a GetLocationAsync (passing both a GeolocationRequest and CancellationToken instance) in the background and update the app accordingly upon the more accurate and recent position.
re: https://learn.microsoft.com/en-us/xamarin/essentials/geolocation?tabs=ios

Android Beacon Library Reference Application Help (didEnterRegion function)

My region is:
Region region = new Region("backgroundRegion", Identifier.parse("24DDF411-8CF1-440C87CD-E368DAF9C93E"), null, null);
When I start the program I get this message:
06-26 18:03:21.061 7394-7394/? D/BeaconReferenceApp: setting up background monitoring for beacons and power saving
But it doesn't enter in any didEnterRegion function
So, I removed this line: backgroundPowerSaver = new BackgroundPowerSaver(this);
And change scanning times, as it follows:
beaconManager.setBackgroundScanPeriod(1100l);
beaconManager.setBackgroundBetweenScanPeriod(10000l-1100l);
I checked my Beacon UUID and they are 24DDF411-8CF1-440C87CD-E368DAF9C93E
So what is wrong? Why the app doesn't go to the didEnterRegion function?
I already made it work to work with other than AltBeacons... (ranging function works ok!)
My final goal is to get current time when a beacon is discovered...
A few possibilities:
If you are already in the beacon region, you won't get a second callback until the beacon disappears (turn it off for 30 seconds or so, then turn it back on while the app is running.) Alternatively, you can look for a call do didDetermineStateForRegion which is always called when your app starts up, with a flag that tells you if you are inside or outside.
Make sure you have granted runtime permissions to location.
Make sure location is turned on for your phone in settings.
Make sure the beacon is transmitting that identifier using the Locate app https://play.google.com/store/apps/details?id=com.radiusnetworks.locate&hl=en
Make sure you have the proper BeaconParser configured. The question is tagged Eddystone, but shows an iBeacon or AltBeacon-style UUID as the first identifier. Do you have a custom beacon parser configured? What beacon type are you trying to detect?

Run background task every X amount of time

I would like to start a service that once in awhile on all platforms has checked is there a notification to appear or not. Is there any nuget to connect all platforms or some examples?
You can use the Device.StartTimer(TimeSpan minutes) method to start a background task that will repeat after the given time span. Here is a code example:
var minutes = TimeSpan.FromMinutes (3);
Device.StartTimer (minutes, () => {
// call your method to check for notifications here
// Returning true means you want to repeat this timer
return true;
});
This is included with Xamarin Forms, so you don't need any platform specific logic.
http://iosapi.xamarin.com/index.aspx?link=M%3AXamarin.Forms.Device.StartTimer(System.TimeSpan%2CSystem.Func%7BSystem.Boolean%7D)
I think that the best that you can do is following:
Unfortunately, the way that these two platforms have evolved to handle executing background code is completely different. As such, there is no way that we can abstract the backgrounding feature into the Xamarin.Forms library. Instead, we going to continue to rely on the native APIs to execute our shared background task.
Further information for this topic can be found here:
https://robgibbens.com/backgrounding-with-xamarin-forms/

OSX Cocoa input source detect change

Does anyone know how to detect when the user changes the current input source in OSX?
I can call TISCopyCurrentKeyboardInputSource() to find out which input source ID is being used like this:
TISInputSourceRef isource = TISCopyCurrentKeyboardInputSource();
if ( isource == NULL )
{
cerr << "Couldn't get the current input source\n.";
return -1;
}
CFStringRef id = (CFStringRef)TISGetInputSourceProperty(
isource,
kTISPropertyInputSourceID);
CFRelease(isource);
If my input source is "German", then id ends up being "com.apple.keylayout.German", which is mostly what I want. Except:
The results of TISCopyCurrentKeyboardInputSource() doesn't change once my process starts? In particular, I can call TISCopyCurrentKeyboardInputSource() in a loop and switch my input source, but TISCopyCurrentKeyboardInputSource() keeps returning the input source that my process started with.
I'd really like to be notified when the input source changes. Is there any way of doing this? To get a notification or an event of some kind telling me that the input source has been changed?
You can observe the NSTextInputContextKeyboardSelectionDidChangeNotification notification posted by NSTextInputContext to the default Cocoa notification center. Alternatively, you can observe the kTISNotifySelectedKeyboardInputSourceChanged notification delivered via the Core Foundation distributed notification center.
However, any such change starts in a system process external to your app. The system then notifies the frameworks in each app process. The frameworks can only receive such notifications when it is allowed to run its event loop. Likewise, if you're observing the distributed notification yourself, that can only happen when the event loop (or at least the main thread's run loop) is allowed to run.
So, that explains why running a loop which repeatedly checks the result of TISCopyCurrentKeyboardInputSource() doesn't work. You're not allowing the frameworks to monitor the channel over which it would be informed of the change. If, rather than a loop, you were to use a repeating timer with a low enough frequency that other stuff has a chance to run, and you returned control to the app's event loop, you would see the result of TISCopyCurrentKeyboardInputSource() changing.

Resources