I'm developing an app based in GPS services and i must track the location of the user continuously, like HERE Maps.
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.MovementThreshold = 20; //Doesn't matter the value I put here, it won't work
geolocator.PositionChanged += geolocator_PositionChanged;
void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
Dispatcher.BeginInvoke(() =>
{
if(args.Position != null)
{
myPosition = args.Position.Coordinate.ToGeoCoordinate();
UpDateData();
}
});
}
(I've tried with GeoCoordinateWatcher but i got nothing).
These functions work perfectly when i'm standing at the same place or moving very slowly, but if i enter in a car and start to drive the app crashes after few seconds, and I don't know WHY.
I've searched a lot of codes with the same finality and all of them don't work.
Do you know any other solution for that problem or have already found yourselves in the same position as mine ?
try
{
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.ReportInterval = 2000;
geolocator.PositionChanged += geolocator_PositionChanged;
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Location is Disabled in Phone Settings.");
}
private void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
try
{
Dispatcher.BeginInvoke(() =>
{
if (args.Position != null && args.Position.Coordinate.ToGeoCoordinate() != myPosition)
{
if(args.Position.Coordinate.Accuracy <= 1500)
{
myPosition = args.Position.Coordinate.ToGeoCoordinate();
UpDateMyPositionCircle(args.Position.Coordinate.Accuracy);
}
}
});
}
catch (TargetInvocationException tie)
{
if (tie.Data == null) throw;
else MessageBox.Show("TargetInvocationException while Tracking: " + tie.InnerException.ToString());
}
catch(SystemException se)
{
if (se.Data == null) throw;
else MessageBox.Show("SystemException while Tracking: " + se.InnerException.ToString());
}
catch(Exception ex)
{
if (ex.Data == null) throw;
else MessageBox.Show("Exception while Tracking: " + ex.InnerException.ToString());
}
}
Related
I'm using AvalonDock and I would serialize and deserialize my layout. But the callback (where I use the ContentId for create an instance of correct object) is not always called. For this reason the loaded not work correctly. I have tried to add one "try-catch", but not thrown exception.
This is my code:
` var layoutSerializer = new XmlLayoutSerializer(manager);
layoutSerializer.LayoutSerializationCallback += (s, e) =>
{
MyClass item;
if (items.TryGetValue(e.Model.ContentId, out item))
{
e.Content = item;
var tool = item as IMyClassToolApp;
var anchorable = e.Model as LayoutAnchorable;
var document = item as IMyClassDocumentApp;
var layoutDocument = e.Model as LayoutDocument;
if (tool != null && anchorable != null)
{
addToolCallback(tool);
tool.IsVisible = anchorable.IsVisible;
tool.IsSelected = e.Model.IsSelected;
return;
}
if (document != null && layoutDocument != null)
{
addDocumentCallback(document);
// Nasty hack to get around issue that occurs if documents are loaded from state,
// and more documents are opened programmatically.
layoutDocument.GetType().GetProperty("IsLastFocusedDocument").SetValue(layoutDocument, false, null);
document.IsVisible = true;
document.IsSelected = layoutDocument.IsSelected;
return;
}
}
e.Cancel = true;
};
try
{
layoutSerializer.Deserialize(stream);
}
catch
{
return false;
}`
Thank you for your help!
Are you sure your stream is O.K? If for example configuration file does not exist LayoutSerializationCallback method will not be called.
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
try
{
MainWindow.logger.Debug("Entering: {0}", "MainWindow_Loaded");
string filePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
#"Jofta\Analyzer\configs\AvalonDock.config");
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
XmlLayoutSerializer serializer = new XmlLayoutSerializer(this.dockingManager);
serializer.LayoutSerializationCallback += this.Serializer_LayoutSerializationCallback;
serializer.Deserialize(filePath);
}
MainWindow.logger.Debug("Exiting: {0}", "MainWindow_Loaded");
}
catch (Exception ex)
{
MainWindow.logger.Error("Exception in: {0}", "MainWindow_Loaded");
MainWindow.logger.Error("Message: {0}", ex.Message);
}
}
private void Serializer_LayoutSerializationCallback(object sender, LayoutSerializationCallbackEventArgs e)
{
try
{
MainWindow.logger.Debug("Entering: {0}", "serializer_LayoutSerializationCallback");
if (e.Model.ContentId == ObjectExplorerViewModel.AnchorableContentId)
{
e.Content = Workspace.Instance.ObjectExplorer;
return;
}
// ...
// ...
MainWindow.logger.Debug("Exiting: {0}", "serializer_LayoutSerializationCallback");
}
catch (Exception ex)
{
MainWindow.logger.Error("Exception in: {0}", "serializer_LayoutSerializationCallback");
MainWindow.logger.Error("Message: {0}", ex.Message);
}
}
I'm developing an app based in GPS services and i must track the location of the user continuously, like HERE Maps, and I'm using the code bellow:
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.MovementThreshold = 20; //Doesn't matter the value I put here, it won't work
geolocator.PositionChanged += geolocator_PositionChanged;
void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
Dispatcher.BeginInvoke(() =>
{
if(args.Position != null)
{
myPosition = args.Position.Coordinate.ToGeoCoordinate();
UpDateData();
}
});
}
The problem is: I got a System.Reflection.TargetInvocationException
Do you have any solutuon for that kind of problem ?
try
{
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.ReportInterval = 2000;
geolocator.PositionChanged += geolocator_PositionChanged;
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Location is Disabled in Phone Settings.");
}
private void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
try
{
Dispatcher.BeginInvoke(() =>
{
if (args.Position != null && args.Position.Coordinate.ToGeoCoordinate() != myPosition)
{
if(args.Position.Coordinate.Accuracy <= 1500)
{
myPosition = args.Position.Coordinate.ToGeoCoordinate();
UpDateMyPositionCircle(args.Position.Coordinate.Accuracy);
}
}
});
}
catch (TargetInvocationException tie)
{
if (tie.Data == null) throw;
else MessageBox.Show("TargetInvocationException while Tracking: " + tie.InnerException.ToString());
}
catch(SystemException se)
{
if (se.Data == null) throw;
else MessageBox.Show("SystemException while Tracking: " + se.InnerException.ToString());
}
catch(Exception ex)
{
if (ex.Data == null) throw;
else MessageBox.Show("Exception while Tracking: " + ex.InnerException.ToString());
}
}
Most likely this error is causes by the location not being marked as on in your application manifest file
As #Stuart mentioned make sure that you've ticked the ID_CAP_LOCATION from your AppManifest file. If you don’t do this your app will throw an exception and when you try deploy it during development and will cause your app to fail.
How to continuously track the phone's location for Windows Phone 8
current I use this code to get GPS:
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.Default;
geolocator.DesiredAccuracyInMeters = 50;
try
{
Geoposition currentPosition = await geolocator.GetGeopositionAsync(TimeSpan.FromSeconds(120), TimeSpan.FromSeconds(30));
MyCoordinate = new GeoCoordinate(currentPosition.Coordinate.Latitude, currentPosition.Coordinate.Longitude);
}
catch (Exception ex)
{
if (ex.Message.Contains("This operation returned because the timeout period expired."))
{
MessageBox.Show("GPS is taking too long too complete. Pleaes try again.");
this.SetProgressIndicator(false);
RadBusyIndicator.IsRunning = false;
return;
}
else
{
this.SetProgressIndicator(false);
RadBusyIndicator.IsRunning = false;
return;
}
};
But it always takes too long to complete, as you can see I set timeout 30s but not sure why
it doesn't show timeout exception when took more than 30s.
I'm getting stuck on this issue. Does anyone have any idea?
Make sure the wifi or cellphone device is on, this enables the fallback methods to be used when the GPS device can't find a signal.
Someone with more or less the same problem made another thread in here:
GetGeopositionAsync does not return
More information on the GeoLocator class:
http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.geolocation.geolocator#properties
I don't know why too, but TimeSpanis realy slow, but doing it with ReportInterval works fine:
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.ReportInterval = 2000;
geolocator.PositionChanged += geolocator_PositionChanged;
private void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
try
{
Dispatcher.BeginInvoke(() =>
{
myPosition = args.Position.Coordinate.ToGeoCoordinate();
});
}
catch(Exception ex)
{
if (ex.Data == null) throw;
else MessageBox.Show("Exception while Tracking: " + ex.InnerException.ToString());
}
}
OK, My issue is quite simple.
I've managed to turn the flash On (and keep it On).
However, I'm still not sure how to turn it off (lol).
Here's my code :
var sensorLocation = CameraSensorLocation.Back;
try
{
// get the AudioViceoCaptureDevice
var avDevice = await AudioVideoCaptureDevice.OpenAsync(sensorLocation,
AudioVideoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation).First());
// turn flashlight on
var supportedCameraModes = AudioVideoCaptureDevice
.GetSupportedPropertyValues(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);
if (supportedCameraModes.ToList().Contains((UInt32)VideoTorchMode.On))
{
avDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
// set flash power to maxinum
avDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchPower,
AudioVideoCaptureDevice.GetSupportedPropertyRange(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchPower).Max);
}
else
{
turnWhiteScreen(true);
}
}
catch (Exception ex)
{
// Flashlight isn't supported on this device, instead show a White Screen as the flash light
turnWhiteScreen(true);
}
Any ideas?
P.S.
I imagined that converting .ons to .offs could have worked, but it doesn't.
This has been tested on a HTC 8S and Lumia 820.
It looks like you can't retrieve the acquisition device twice (I'm not sure why), so you should store it in a property:
protected AudioVideoCaptureDevice Device { get; set; }
private async void ButtonTurnOn_Click(object sender, RoutedEventArgs e)
{
var sensorLocation = CameraSensorLocation.Back;
try
{
if (this.Device == null)
{
// get the AudioViceoCaptureDevice
this.Device = await AudioVideoCaptureDevice.OpenAsync(sensorLocation,
AudioVideoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation).First());
}
// turn flashlight on
var supportedCameraModes = AudioVideoCaptureDevice
.GetSupportedPropertyValues(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);
if (supportedCameraModes.ToList().Contains((UInt32)VideoTorchMode.On))
{
this.Device.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
// set flash power to maxinum
this.Device.SetProperty(KnownCameraAudioVideoProperties.VideoTorchPower,
AudioVideoCaptureDevice.GetSupportedPropertyRange(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchPower).Max);
}
else
{
turnWhiteScreen(true);
}
}
catch (Exception ex)
{
// Flashlight isn't supported on this device, instead show a White Screen as the flash light
turnWhiteScreen(true);
}
}
Then, to turn it off:
private void ButtonTurnOff_Click(object sender, RoutedEventArgs e)
{
var sensorLocation = CameraSensorLocation.Back;
try
{
// turn flashlight on
var supportedCameraModes = AudioVideoCaptureDevice
.GetSupportedPropertyValues(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);
if (this.Device != null && supportedCameraModes.ToList().Contains((UInt32)VideoTorchMode.Off))
{
this.Device.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.Off);
}
else
{
turnWhiteScreen(false);
}
}
catch (Exception ex)
{
// Flashlight isn't supported on this device, instead show a White Screen as the flash light
turnWhiteScreen(false);
}
}
Try this one
private static VideoTorchMode _videoTorchMode = VideoTorchMode.Off;
private AudioVideoCaptureDevice _videoRecordingDevice;
Check torch is exist in device.
private async void CheckTorch() {
if(AudioVideoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Back) &&
AudioVideoCaptureDevice.GetSupportedPropertyValues(CameraSensorLocation.Back, KnownCameraAudioVideoProperties.VideoTorchMode).ToList().Contains((UInt32)VideoTorchMode.On)) {
var temp = AudioVideoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back)[0];
var resolution = new Windows.Foundation.Size(temp .Width, temp .Height);
_videoRecordingDevice = await AudioVideoCaptureDevice.OpenAsync(CameraSensorLocation.Back, resolution);
}
else
MessageBox.Show("Your device does not support torch");
}
To change torch state
private void SetTorchMode(){
try {
if (BackgroundHandler.Instance.IsBackTorchExist) {
if (_videoTorchMode == VideoTorchMode.Off) {
_videoRecordingDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
_videoTorchMode = VideoTorchMode.On;
}
else {
_videoRecordingDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.Off);
_videoTorchMode = VideoTorchMode.Off;
}
}
}
catch (Exception ex){ }
}
First of all, sorry for my English :(.
Hi, I've this code to download multiple files at once, but it's very glitchy when I'm downloading small files. If I lets say download a file that's 80 KB, then the label where I display the progress is spacing out :(.
This is the code I have right now:
bgwrkSplash.ReportProgress(44, 44444444444444);
ChangeText(lblStatus, "Downloading files to temp directory...", Color.Black);
DownloadFile();
resetEvent.WaitOne();
#region Download Handler
private void DownloadFile()
{
if (_downloadUrls.Any())
{
_intCurrentProgressValue = prgSplashStatus.Value;
_client.DownloadProgressChanged += client_DownloadProgressChanged;
_client.DownloadFileCompleted += client_DownloadFileCompleted;
var url = _downloadUrls.Dequeue();
var uri = new Uri(url);
_strFileName = Path.GetFileName(uri.LocalPath);
_client.DownloadFileAsync(new Uri(url), _strTempLocation + _strFileName);
}
}
private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
try
{
_byteCountFormatter.Add(new ByteCountFormatter {DataSize = e.BytesReceived, Time = DateTime.Now});
_byteCountFormatter = _byteCountFormatter.Skip(Math.Min(0, _byteCountFormatter.Count - 6)).ToList();
var speed = (_byteCountFormatter.Last().DataSize - _byteCountFormatter.First().DataSize)/
(_byteCountFormatter.Last().Time - _byteCountFormatter.First().Time).TotalSeconds;
var timeRemaining = TimeSpan.FromSeconds((e.TotalBytesToReceive - e.BytesReceived)/speed);
ChangeText(lblStatus, string.Format(
"Downloading {0} - {1} - {2} of {3} ({4})",
_strFileName,
ByteCountFormatter.FormatTime(timeRemaining),
ByteCountFormatter.FormatDataSize(e.BytesReceived),
ByteCountFormatter.FormatDataSize(e.TotalBytesToReceive),
ByteCountFormatter.FormatDataSpeed(speed)), Color.Black);
ChangeProgress(prgSplashStatus, e.ProgressPercentage);
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
try
{
try
{
if (e.Error != null)
{
throw e.Error;
}
if (e.Cancelled)
{
}
DownloadFile();
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
if (!_client.IsBusy)
{
ChangeProgress(prgSplashStatus, _intCurrentProgressValue);
resetEvent.Set();
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
#endregion
I've removed the Time Remaining part and it all goes smoothly now, thanks all!