Getting GPS coordinates on Windows phone 7 - gps

How can I get the current GPS coordinates on Windows Phone 7?

Here's a simple example:
GeoCoordinateWatcher watcher;
watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default)
{
MovementThreshold = 20
};
watcher.PositionChanged += this.watcher_PositionChanged;
watcher.StatusChanged += this.watcher_StatusChanged;
watcher.Start();
private void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
switch (e.Status)
{
case GeoPositionStatus.Disabled:
// location is unsupported on this device
break;
case GeoPositionStatus.NoData:
// data unavailable
break;
}
}
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
var epl = e.Position.Location;
// Access the position information thusly:
epl.Latitude.ToString("0.000");
epl.Longitude.ToString("0.000");
epl.Altitude.ToString();
epl.HorizontalAccuracy.ToString();
epl.VerticalAccuracy.ToString();
epl.Course.ToString();
epl.Speed.ToString();
e.Position.Timestamp.LocalDateTime.ToString();
}

GeoCoordinateWatcher is the class that provides this functionality. There is a How To, a sample and some other resources on MSDN.

Related

Real time GPS UWP

I really want to know how do I can update the position of the user in the map while the UWP app was running in bakground
Here is my code right now
private async void PinPoints()
{
//Pin point to the map
Windows.Devices.Geolocation.Geopoint position = await Library.Position();
double lat = position.Position.Latitude;
double lon = position.Position.Longitude;
//Geoposition alttest = await Library.Temp();
//alt = alttest.Coordinate.Altitude;
DependencyObject marker = Library.Marker(""
//+ Environment.NewLine + "Altitude " + alt
);
Display.Children.Add(marker);
Windows.UI.Xaml.Controls.Maps.MapControl.SetLocation(marker, position);
Windows.UI.Xaml.Controls.Maps.MapControl.SetNormalizedAnchorPoint(marker, new Point(0.5, 0.5));
Display.LandmarksVisible = true;
Display.ZoomLevel = 16;
Display.Center = position;
}
This function will pinpoint the current location for me but it will do only when user open this page due to I've put it in the public Map() {}
Current : Get the location when open map page and when I walk the map still be the same place
What I want : The position keep changing while I move on and also run on background (If application is close location data still changed)
Is there any code to solve this location problem if I have to add code where should I fix and what should I do?
Additional now I perform the background (Not sure is it work or not) by create the Window Runtime Component (Universal) with class like this
*I already put this project as the reference of the main one
namespace BackgroundRunning
{
public sealed class TaskBG : IBackgroundTask
{
BackgroundTaskDeferral _deferral = null;
Accelerometer _accelerometer = null;
Geolocator _locator = new Geolocator();
public void Run(IBackgroundTaskInstance taskInstance)
{
_deferral = taskInstance.GetDeferral();
try
{
// force gps quality readings
_locator.DesiredAccuracy = PositionAccuracy.High;
taskInstance.Canceled += taskInstance_Canceled;
_accelerometer = Windows.Devices.Sensors.Accelerometer.GetDefault();
_accelerometer.ReportInterval = _accelerometer.MinimumReportInterval > 5000 ? _accelerometer.MinimumReportInterval : 5000;
_accelerometer.ReadingChanged += accelerometer_ReadingChanged;
}
catch (Exception ex)
{
// Add your chosen analytics here
System.Diagnostics.Debug.WriteLine(ex);
}
}
void taskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
_deferral.Complete();
}
async void accelerometer_ReadingChanged(Windows.Devices.Sensors.Accelerometer sender, Windows.Devices.Sensors.AccelerometerReadingChangedEventArgs args)
{
try
{
if (_locator.LocationStatus != PositionStatus.Disabled)
{
try
{
Geoposition pos = await _locator.GetGeopositionAsync();
}
catch (Exception ex)
{
if (ex.HResult != unchecked((int)0x800705b4))
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
public void Dispose()
{
if (_accelerometer != null)
{
_accelerometer.ReadingChanged -= accelerometer_ReadingChanged;
_accelerometer.ReportInterval = 0;
}
}
}
}
Your Solution :
Make 3 projects in your solution.
1> Background Task "references App_Code"
2> App_Code "contains calculations,mostly Backend Code"
3> Map(Main Project) "references App_Code"
Register a background Task to your project and specify the time interval after which it should run again
Scenario 1> App Open,User Requests Update
Trigger Your background Task from code behind.
Scenario 2> App Closed,Not Being Used
Run your background task!
So basically keep your backgroundTask simple(make it a class in whose run method you just call the proper App_Code Classes Method) and all calculations that you want to happen in the background keep them in App_Code. Also, if I am no wrong the minimum interval between which a background Task is triggered by itself cannot be set below 15 minutes.
For real-time you could look at SignalR ( can't help any further here)

Capturing Black image with Flash_ON in Nexus 4 in android

I am using custom camera in android.When i am capturing image with Flash_ON, the image is too dark almost black in Nexus 4 only.But it is fine on other devices.Please help me .
My code is given below :-
CameraInfo cameraInfo = new CameraInfo();
Camera.getCameraInfo(cameraId, cameraInfo);
Camera.Parameters parameters = camera.getParameters();
Size bestPreviewSize = determineBestPreviewSize(parameters);
Size bestPictureSize = determineBestPictureSize(parameters);
mSize = bestPreviewSize;
parameters.setPreviewSize(bestPreviewSize.width,.setPreviewSize(bestPreviewSize.width,
parameters.setPictureSize(bestPictureSize.width, bestPictureSize.height);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
} else {
parameters.setFlashMode(Parameters.FLASH_MODE_ON);
parameters.setSceneMode(Parameters.SCENE_MODE_AUTO);
parameters.setFocusMode(Parameters.FOCUS_MODE_AUTO);
}
camera.setParameters(parameters);
Just change the value of Parameter you need to set as follows
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
Flash should turn off automatically. If it doesn't then turn off it manually in shutter callback
ShutterCallback shutterCallback = new ShutterCallback() {
#Override
public void onShutter() {
try {
Parameters params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
} catch (Exception e) {
}
}
};

CompositionTarget.Rendering doesn't like my event handler in XAML

I'm converting a Windows Phone 7 app to Windows Store, so I'm moving over to Xaml. I have a method that runs at a certain point to update the data on the screen. It either assigns or removes an event handler delegate to the CompositionTarget.Rendering event. The message I get is No overload for 'OnCompositionTargetRendering' matches delegate 'System.EventHandler' '
Here's what I have:
private void CheckCompleted()
{
Color completeColor;
if (this.DecryptedText.ToString().ToUpper() == this.ThisPuzzle.QuoteText.ToUpper())
{
// We're done!!! ...
CompositionTarget.Rendering -= this.OnCompositionTargetRendering;// new EventHandler(this.OnCompositionTargetRendering);
...
}
else
{
...
CompositionTarget.Rendering += this.OnCompositionTargetRendering;// new EventHandler(this.OnCompositionTargetRendering);
...
}
}
protected void OnCompositionTargetRendering(object sender, EventArgs args)
{
this.DisplayTime();
if (ThisPuzzle != null)
{
foreach (UIElement thisElement in Letters.Children)
{
...
}
}
}
If you check the documentation CompositionTarget.Rendering is of type EventHandler<object> in Windows Store apps and not of type EventHandler as in Silverlight.
This means you need to change the signature of your event handler accordingly to:
protected void OnCompositionTargetRendering(object sender, object args)

Java - pressing a direction key and having it move smoothly

When I press a direction key to move the object in that direction, it moves once, pauses momentarily, then moves again. Kind of like how if I want to type "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", I would hold "a" key down, but after the first "a" there is a pause then the rest of the "a"'s are typed. How do I remove that pause in KeyListener? Thank you.
This is the key repetition feature that the OS provides, so there is no way around the pauses.
The way most games gets around this is to keep an array of the current state of all required keys and check periodically on them (for example in the game loop) and act on that (e.g move).
public class KTest extends JFrame implements KeyListener {
private boolean[] keyState = new boolean[256];
public static void main(String[] args) {
new KeyTest();
int xVelocity = 0;
int x = 0;
while(1) {
xVelocity = 0;
if(keyState[KeyEvent.VK_LEFT]) {
xVelocity = -5;
}
x += xVelocity;
}
}
KTest() {
this.addKeyListener(this);
}
void keyPressed(KeyEvent e) {
key_state[e.getKeyCode()] = true;
}
void keyReleased(KeyEvent e) {
key_state[e.getKeyCode()] = false;
}
}
Base class taken from: http://content.gpwiki.org/index.php/Java:Tutorials:Key_States

Using KinectColorViewer in SDK1.5

I am trying to use a KinectColorViewer in a project using Kinect for windows (sdk 1.5). In the kinect explorer example, the KinectColorViewer componant had a KinectSensorManager component that is binded. In the xaml file we have:
<kt:KinectColorViewer x:Name="ColorViewer" KinectSensorManager="{Binding KinectSensorManager}" CollectFrameRate="True" RetainImageOnSensorChange="True" />
I have a lot of trouble reproduccing the same concept in other projects. I have used the Microsoft.Kinect.Toolkit's KinectSensorChooser, KinectSensorChooserUI and the Mirosoft.Sampels.Kinect.wpfviewers KinectColorViewer. Tried to bind the KinectSensorManager of The colorViewer to the UI element and follows.
<my:KinectColorViewer Width="200" Height="200" HorizontalAlignment="Left" Margin="198,12,0,0" Name="kinectColorViewer1" VerticalAlignment="Top" KinectSensorManager="{Binding ElementName=kinectSensorChooserUI1, Path=KinectSensorChooser.Kinect}" />
both attempts were unsuccesfull. Has anyone used the ColorViwer, DepthViwer and SkeletonViewer using the new SDK? Figuring that our would be great...
To bind the KinectSensorManager, I added the following code to the back end:
public partial class MainWindow : Window
{
public KinectSensorManager KinectSensorManager { get; set;}
private void WindowLoaded(object sender, RoutedEventArgs e)
{
KinectSensorManager = new KinectSensorManager();
KinectSensorManager.KinectSensorChanged += new EventHandler<KinectSensorManagerEventArgs<KinectSensor>>(KinectSensorManager_KinectSensorChanged);
// Look through all sensors and start the first connected one.
// This requires that a Kinect is connected at the time of app startup.
foreach (var potentialSensor in KinectSensor.KinectSensors)
{
if (potentialSensor.Status == KinectStatus.Connected)
{
this.sensor = potentialSensor;
break;
}
}
if (null != this.sensor)
{
// Turn on the skeleton stream to receive skeleton frames
this.sensor.SkeletonStream.Enable();
this.sensor.DepthStream.Enable();
this.sensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
this.sensor.AllFramesReady += new System.EventHandler<AllFramesReadyEventArgs>(sensor_AllFramesReady);
this.sensor.SkeletonFrameReady += this.SensorSkeletonFrameReady;
// Start the sensor!
try
{
this.sensor.Start();
}
catch (IOException)
{
this.sensor = null;
}
var kinectSensorBinding = new Binding("KinectSensor") { Source = this.sensor };
BindingOperations.SetBinding(this.KinectSensorManager, KinectSensorManager.KinectSensorProperty, kinectSensorBinding);
}
if (null == this.sensor)
{
this.statusBarText.Text = Properties.Resources.NoKinectReady;
}
}
and the Xaml file:
<kt:KinectColorViewer Width="191" Height="83" Grid.Column="3" KinectSensorManager="{Binding KinectSensorManager}" HorizontalAlignment="Left" Margin="17,236,0,0" Name="kinectColorViewer1" VerticalAlignment="Top" />
but I still dont get any color stream.
You binding statement is incorrect. "KinectSensorChooser.Kinect" is a reference to hardware (i.e., the Kinect) selected by the KinectSensorChooser -- it is not the KinectSensorManager.
You should be binding to the KinectSensorManager in the same way the examples show you. Is there something special you are trying to do that would lead you to bind it differently?
Your main class should start out something like this:
// automatically finds a Kinect for you
private readonly KinectSensorChooser sensorChooser = new KinectSensorChooser();
// the bindable sensor property
public KinectSensorManager KinectSensorManager { get; private set; }
public MainViewModel()
{
if (IsInDesignMode) {
// load design mode only content
}
else
{
// initialize the Kinect sensor manager
KinectSensorManager = new KinectSensorManager();
KinectSensorManager.KinectSensorChanged += this.KinectSensorChanged;
// locate an available sensor
sensorChooser.Start();
// bind chooser's sensor value to the local sensor manager
var kinectSensorBinding =
new Binding("Kinect") { Source = this.sensorChooser };
BindingOperations.SetBinding(
this.KinectSensorManager,
KinectSensorManager.KinectSensorProperty,
kinectSensorBinding);
}
}
#region Kinect Discovery & Setup
private void KinectSensorChanged(object sender,
KinectSensorManagerEventArgs<KinectSensor> args)
{
if (null != args.OldValue)
UninitializeKinectServices(args.OldValue);
if (null != args.NewValue)
InitializeKinectServices(KinectSensorManager, args.NewValue);
}
// Kinect enabled apps should customize which Kinect services it initializes here.
private void InitializeKinectServices(
KinectSensorManager kinectSensorManager,
KinectSensor sensor)
{
// Application should enable all streams first.
// configure the color stream
kinectSensorManager.ColorFormat =
ColorImageFormat.RgbResolution640x480Fps30;
kinectSensorManager.ColorStreamEnabled = true;
// configure the depth stream
kinectSensorManager.DepthStreamEnabled = true;
kinectSensorManager.TransformSmoothParameters =
new TransformSmoothParameters
{
Smoothing = 0.5f,
Correction = 0.5f,
Prediction = 0.5f,
JitterRadius = 0.05f,
MaxDeviationRadius = 0.04f
};
// configure the skeleton stream
sensor.SkeletonFrameReady += OnSkeletonFrameReady;
kinectSensorManager.SkeletonStreamEnabled = true;
}
// Kinect enabled apps should uninitialize all Kinect services that were initialized in InitializeKinectServices() here.
private void UninitializeKinectServices(KinectSensor sensor)
{
sensor.SkeletonFrameReady -= this.OnSkeletonFrameReady;
}
#endregion Kinect Discovery & Setup
You can then bind to the manager from your View as shown by the examples.
You make need to also set the DataContext, by putting the following into the constructor:
DataContext = this;