Accelerometer event handler doesn't respond after few triggers. WP8 - windows-phone-8

I am building windows app for reading and displaying the x,y and z values on a text block.
The application works for few execution but stops responding after few changes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp9.Resources;
using Microsoft.Devices.Sensors;
using Microsoft.Xna.Framework;
namespace PhoneApp9
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
Accelerometer acc = new Accelerometer();
acc.CurrentValueChanged +=acc_ReadingChanged;
try
{
acc.Start();
}
catch(Exception ex)
{
tbk.Text = ex.ToString();
}
}
private void acc_ReadingChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
{
try
{
System.Threading.Thread.Sleep(1);
Dispatcher.BeginInvoke( () =>
{
tbk.Text = "X:" + e.SensorReading.Acceleration.X.ToString("0.00");
tbk.Text += "\nY:" + e.SensorReading.Acceleration.Y.ToString("0.00");
tbk.Text += "\nZ:" + e.SensorReading.Acceleration.Z.ToString("0.00");
});
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
//throw new NotImplementedException();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (Accelerometer.IsSupported==true)
MessageBox.Show("exist");
else
MessageBox.Show("not exïst");
}
}
}
}
handler( ) stops executing after few trial. This is un predicted behavior.

Why do you use System.Threading.Thread.Sleep(1) ??
Dispatcher.BeginInvoke add an event to the UI eventloop. Maybe accelerometer update is faster than the ui event-loop execution. So the ui eventloop grow and your application is blocked after few seconds. You could try to add a boolean to control it.
bool displaySensorData = false;
private void acc_ReadingChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
{
if(displaySensorData ) return;
try
{
displaySensorData = true;
Dispatcher.BeginInvoke( () =>
{
tbk.Text = "X:" + e.SensorReading.Acceleration.X.ToString("0.00");
tbk.Text += "\nY:" + e.SensorReading.Acceleration.Y.ToString("0.00");
tbk.Text += "\nZ:" + e.SensorReading.Acceleration.Z.ToString("0.00");
displaySensorData = false;
});
}
catch (Exception ex)
{
displaySensorData = false;
MessageBox.Show(ex.ToString());
}
//throw new NotImplementedException();
}

Related

How to get a Toast Notification when app running in foreground in wp8

I want to implement the "toast" notification inside my windows phone application. I'm implementing push message's, but I want them to show always. No matter if the application is running or not. The push notification will handle it when the application is closed, but not when it is running. Also if I create a shelltoast manually it won't show. To make it more difficult I can't use any external dll's. I only want to use code. What would be the best way to do this? I already know about the ToastNotificationRecieved event. I want to know how to implement it so that it will show a "toast" like message without using a framework
My code is below
PushPlugin.cs(c# code)
public void showToastNotification(string options)
{
ShellToast toast;
if (!TryDeserializeOptions(options, out toast))
{
this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
Deployment.Current.Dispatcher.BeginInvoke(toast.Show);
}
public void PushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
{
var toast = new PushNotification
{
Type = "toast"
};
foreach (var item in e.Collection)
{
toast.JsonContent.Add(item.Key, item.Value);
}
this.ExecuteCallback(this.pushOptions.NotificationCallback, JsonConvert.SerializeObject(toast));
}
In javascript
function onNotificationWP8(data) {
var pushNotification;
pushNotification = window.plugins.pushNotification;
pushNotification.showToastNotification(successHandler, errorHandler,
{
"Title": data.jsonContent["wp:Text1"], "Content": data.jsonContent["wp:Text2"], "NavigationUri": data.jsonContent["wp:Param"]
});
}
On devices without Windows Phone 8 Update 3, toast notifications are not displayed when the target app is running in the foreground. On devices with Windows Phone 8 Update 3, toast notifications are displayed when the target app is running in the foreground, but is obscured by other activity such as a phone call or the lock screen.
The following C# code example shows the properties used to create a toast notification using local code.
// Create a toast notification.
// The toast notification will not be shown if the foreground app is running.
ShellToast toast = new ShellToast();
toast.Title = "[title]";
toast.Content = "[content]";
toast.Show();
This thread has it all you looking for
public static class Notification
{
public static string ChannelURI = string.Empty;
public static void MainNotificationCallFunction()
{
try
{
NotificationMessage("Test Notification");
}
catch (Exception e)
{ }
}
public static void NotificationMessage(string Message)
{
try
{
ToastTemplateType toastType = ToastTemplateType.ToastText02;
XmlDocument toastXmlJob = ToastNotificationManager.GetTemplateContent(toastType);
XmlNodeList toastTextElementJob = toastXmlJob.GetElementsByTagName("text");
toastTextElementJob[0].AppendChild(toastXmlJob.CreateTextNode(Message));
IXmlNode toastNodeJob = toastXmlJob.SelectSingleNode("/toast");
((XmlElement)toastNodeJob).SetAttribute("duration", "long");
ToastNotification toastJob = new ToastNotification(toastXmlJob);
ToastNotificationManager.CreateToastNotifier().Show(toastJob);
}
catch (Exception e)
{ }
}
public static void PushNotification()
{
try
{
/// Holds the push channel that is created or found.
HttpNotificationChannel pushChannel;
string channelName = "Usman's Channel";
// Try to find the push channel.
pushChannel = HttpNotificationChannel.Find(channelName);
// If the channel was not found, then create a new connection to the push service.
if (pushChannel == null)
{
pushChannel = new HttpNotificationChannel(channelName);
//// Register for all the events before attempting to open the channel.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
pushChannel.Open();
pushChannel.BindToShellTile();
pushChannel.BindToShellToast();
}
else
{
//// The channel was already open, so just register for all the events.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
}
}
catch (Exception ex)
{ }
}
private static void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Display the new URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString());
MessageBox.Show(String.Format("Channel Uri is {0}", e.ChannelUri.ToString()));
});
}
catch (Exception ex)
{ }
}
private static void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
try
{
// Error handling logic for your particular application would be here.
Deployment.Current.Dispatcher.BeginInvoke(() =>
MessageBox.Show(String.Format("A push notification {0} error occurred. {1} ({2}) {3}", e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData)));
}
catch (Exception ex)
{ }
}
private static void PushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
{
try
{
string message;
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
{
message = reader.ReadToEnd();
}
Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(String.Format("Received Notification {0}:\n{1}", DateTime.Now.ToShortTimeString(), message)));
}
catch (Exception ex)
{ }
}
private static void channel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(e.Message, "Error", MessageBoxButton.OK);
});
}
catch (Exception ex)
{ }
}
private static void channel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
//ProgressBarPushNotifications.Visibility = System.Windows.Visibility.Collapsed;
MessageBox.Show(e.ChannelUri.ToString(), "Uri Recieved", MessageBoxButton.OK);
});
}
catch (Exception ex)
{ }
}
private static void channel_ShellToastNotificationReceived(object sender, HttpNotificationEventArgs e)
{
try
{
StringBuilder message = new StringBuilder();
string relativeUri = string.Empty;
message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString());
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
{
message.AppendFormat(reader.ReadToEnd());
}
// Display a dialog of all the fields in the toast.
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(message.ToString());
});
}
catch (Exception ex)
{ }
}
}

Accurate Windows phone 8.1 geolocation?

Im working with windows phone 8.1 geolocation. The problem that I currently have is that my code only shows the first numbers of my coordinate. Example: If the coordinate is "41.233" the app only shows "41.00" . I need it to be as accurate as possible. In case it matters, im using windows phone 8.1 emulator to try the app, not an actual phone.
My code:
public sealed partial class MainPage : Page
{
bool shouldSend = false;
DispatcherTimer timer = new DispatcherTimer();
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
private async Task GetLocation()
{
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.High;
try
{
Geoposition geoposition = await geolocator.GetGeopositionAsync(
maximumAge: TimeSpan.FromSeconds(1),
timeout: TimeSpan.FromSeconds(10)
);
LatitudeTxt.Text = geoposition.Coordinate.Latitude.ToString("0.00");
LongitudeTxt.Text = geoposition.Coordinate.Longitude.ToString("0.00");
LatLonTxt.Text = LatitudeTxt.Text + ", " + LongitudeTxt.Text;
var speed = geoposition.Coordinate.Speed.ToString();
ProcessingTxt.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
string result = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
"http://proyecto-busways.rhcloud.com/colectivos?p=lta123&l=80&d=moyano&lat=" + LatitudeTxt.Text + "&lon=" + LongitudeTxt.Text + "&v=" + speed + "&Accion=Agregar");
request.ContinueTimeout = 4000;
request.Credentials = CredentialCache.DefaultNetworkCredentials;
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
if (response.StatusCode == HttpStatusCode.OK)
{
//To obtain response body
using (Stream streamResponse = response.GetResponseStream())
{
using (StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8))
{
result = streamRead.ReadToEnd();
}
}
}
}
}
catch (Exception ex)
{
ProcessingTxt.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
if ((uint)ex.HResult == 0x80004004)
{
// the application does not have the right capability or the location master switch is off
}
//else
{
// something else happened acquring the location
}
}
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
private async void StartSending_Click(object sender, RoutedEventArgs e)
{
await GetLocation();
timer.Tick += timer_Tick;
timer.Interval = new TimeSpan(0, 0, 5);
timer.Start();
StartSending.IsEnabled = false;
}
async void timer_Tick(object sender, object e)
{
ProcessingTxt.Visibility = Windows.UI.Xaml.Visibility.Visible;
await GetLocation();
}
private void EndSending_Click(object sender, RoutedEventArgs e)
{
timer.Tick -= timer_Tick;
timer.Stop();
StartSending.IsEnabled = true;
EndSending.IsEnabled = false;
}
private void GPS_Tapped(object sender, TappedRoutedEventArgs e)
{
Frame.Navigate(typeof(ContactPage));
}
}
Thanks for your help!
Did you try out the Geolocator.DesiredAccuracyInMeters property?
geolocator.DesiredAccuracyInMeters = 3;
Reference & Sample
In this point LatitudeTxt.Text = geoposition.Coordinate.Latitude.ToString("0.00");
LongitudeTxt.Text = geoposition.Coordinate.Longitude.ToString("0.00");
You indicated that you have 0.00 decimals, for more accuracy you should put 0.000000

WebClient TimeOut Windows Phone 8

I would like to run a task during the waiting of a web request. If the task finishes before the request can return a response, then I would display a message "The server is taking too long". I'm using a WebClient object, how can I manage the time out?
public Class Result
{
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (NavigationContext.QueryString.TryGetValue("critere", out sCritere))
{
try
{
_datamanager = new DataManager();
_datamanager.m_evt_Client_DownloadStringCompleted += OnDownloadStringCompleted;
_datamanager.DownloadXmlData(DataManager.URL_RECHERCHE, sCritere);
//HERE I NEED TO RUN A TIMER If the response is too long i would display a message
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Erreur", MessageBoxButton.OK);
NavigationService.GoBack();
NavigationService.RemoveBackEntry();
}
}
}
}
public Class DataManager
{
public void DownloadXmlData(string uri, string critere = "")
{
try
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.Credentials = new NetworkCredential(UserSaved, PasswordSaved, domain);
client.DownloadStringAsync(new Uri(uri + critere));
}
catch(WebException )
{
throw new WebException(MyExceptionsMessages.Webexception) ;
}
catch (Exception )
{
throw new UnknowException(MyExceptionsMessages.UnknownError);
}
}
public void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//raise Downloadstringcompleted event if error==null
}
}
You can use BackgroundWorker..
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (s, e) =>
{
// your task to do while webclient is downloading
};
bw.RunWorkerCompleted += (s, e) =>
{
// check whether DownloadStringCompleted is fired or not
// if not, cancel the WebClient's asynchronous call and show your message.
client.CancelAsync();
MessageBox.Show("message");
}
client.DownloadStringAsync(uri);
bw.RunWorkerAsync();

I am getting error in LoginAsync method during wp8 App development for sky drive

I am developing a windows phone 8 application to access sky drive. I am getting following error when I call LoginAsync() method-
An exception of type 'Microsoft.Live.LiveAuthException' occurred in mscorlib.ni.dll but was not handled in user code
using System;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Live;
namespace SkyDriveApp
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
LiveConnectClient client;
public MainPage()
{
InitializeComponent();
}
public async void Auth()
{
string clientId = "My_client_id";
LiveAuthClient auth = new LiveAuthClient(clientId);
// var result = await auth.InitializeAsync(new[] { "wl.basic", "wl.signin", "wl.skydrive_update" });
var result = await auth.LoginAsync(new[] { "wl.basic", "wl.signin", "wl.skydrive_update" });
if (result.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(result.Session);
tbMessage.Text = "Connected!";
}
}
private void btnLogin_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
Auth();
}
}
}
I see that you are using provided login buton, try this:
In xaml:
<live:SignInButton Name="skyBtn" ClientId="your client ID" Scopes="wl.signin wl.skydrive wl.skydrive_update" Branding="Skydrive" TextType="Login"/>
In code behind:
private void skyBtn_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
session = e.Session;
client = new LiveConnectClient(session);
tbMessage.Text = "Connected!";
}
else tbMessage.Text = "Not Connected!";
if (e.Error != null)
{
tbMessage.Text = "Not Connected!";
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(e.Error.Message);
});
}
}

Future get() gets nullpointer exeception in java

I'm implementing a function that detects if there is a webcam. This piece of code works fine in windows and I had no problem with it in linux centos OS. Now I'm trying to run the same code in Ubuntu, here an exception is thrown.
Exception in thread "main" java.lang.NullPointerException
at CameraProperties.CheckForCameraPlugin.check(CheckForCameraPlugin.java:51)
at Main.Main.main(Main.java:39)
The code is given below.
public boolean check()
{
boolean b = true;
service = Executors.newFixedThreadPool(1);
task = service.submit(new InitialCameraChecker());
try
{
final String str;
// waits the 10 seconds for the Callable.call to finish.
str = task.get();
if (str.matches("nodevice"))
{
b = false;//Return false if no camera device found
}
else
{
b = true;
}
}
catch (InterruptedException | ExecutionException ex)
{
msgbox.showJoptionPane(15);
}
service.shutdownNow();
return b;
}
The callable class is given below
class InitialCameraChecker implements Callable<String>
{
private List<Integer> devices = new ArrayList<Integer>();
private final static String VERSION_ID = "1.0.0";
private String res;
//Checking for the Camera
public String call()
{
try
{
loadWebcam();
discoverDevices();
if (devices.isEmpty())
{
res = "nodevice";//No we cam device found
}
else
{
res = "founddevice";//Found Web Cam Device
}
}
catch (Exception ex)
{
System.out.println("Exception_logout" + ex.toString());
}
return res;
}
//Discovering the camera device
private void discoverDevices()
{
for (int i = 0; i < 10; i++)
{
CvCapture cap = null;
try
{
cap = cvCreateCameraCapture(i);
int res = cvGrabFrame(cap);
if (res > 0)
{
devices.add(i);
break;
}
}
catch (Exception e)
{
System.out.println("Exception in camaracheck Thread1");
}
finally
{
if (cap != null)
{
try
{
cvReleaseCapture(cap.pointerByReference());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
}
//Loading the dlls for starting the camera
private void loadWebcam()
{
String tmpDir = System.getProperty("java.io.tmpdir");
File faPath = new File(tmpDir + File.separator + "WebcamApplet_" + VERSION_ID.replaceAll("\\.", "-"));
System.setProperty("jna.library.path", faPath.getAbsolutePath());
}
}
Please tell me what is the problem. This works fine in windows.