Windows Phone 8.1 App - Auto Logout (Detect if App is Running) - windows

I am building a Windows 8.1 Universal app, and at the minute specifically I am working on the Windows Phone side of it. The app is an RT app built using the MVVM pattern, and I am using MVVM Light.
The app is for a financial institunion and exposes payment information. As such, there is a security requirement to log the user out of the app if there is no activity after a period of 2 minutes.
I've searched high and low for a solution to this problem. The only one which really works is to set up gestures in the view, and use a DispatchTimer, which expires and redirects to the app lock screen (not the built-in Windows one) after 2 minutes if no gestures have been detected. A gesture resets the timer. Here is some sample code for the gesture setup:
public MainPage()
{
this.InitializeComponent();
//Register the gestures, for the app timeout
this.PointerPressed += MainPage_PointerPressed;
this.PointerMoved += MainPage_PointerMoved;
this.PointerReleased += MainPage_PointerReleased;
gr.CrossSliding += Gr_CrossSliding;
gr.Dragging += Gr_Dragging;
gr.Holding += Gr_Holding;
gr.ManipulationCompleted += Gr_ManipulationCompleted;
gr.ManipulationInertiaStarting += Gr_ManipulationInertiaStarting;
gr.ManipulationStarted += Gr_ManipulationStarted;
gr.ManipulationUpdated += Gr_ManipulationUpdated;
gr.RightTapped += Gr_RightTapped;
gr.Tapped += Gr_Tapped;
gr.GestureSettings = Windows.UI.Input.GestureSettings.ManipulationRotate | Windows.UI.Input.GestureSettings.ManipulationTranslateX | Windows.UI.Input.GestureSettings.ManipulationTranslateY |
Windows.UI.Input.GestureSettings.ManipulationScale | Windows.UI.Input.GestureSettings.ManipulationRotateInertia | Windows.UI.Input.GestureSettings.ManipulationScaleInertia |
Windows.UI.Input.GestureSettings.ManipulationTranslateInertia | Windows.UI.Input.GestureSettings.Tap;
InitializeTimer();
}
There are methods for receiving gesture inputs on the page, like this:
private void Gr_Tapped(Windows.UI.Input.GestureRecognizer sender, Windows.UI.Input.TappedEventArgs args)
{
ResetTimer();
}
And here is my timer code:
private DispatcherTimer _timer2 { get; set; }
int ticks = 0;
private void InitializeTimer()
{
_timer2 = new DispatcherTimer();
_timer2.Tick += timer2_Tick;
_timer2.Interval = new TimeSpan(00, 0, 1);
bool enabled = _timer2.IsEnabled;
_timer2.Start();
}
void timer2_Tick(object sender, object e)
{
ticks++;
if (ticks >= 120)
{
Timeout();
}
}
private void Timeout()
{
_timer2.Stop();
_timer2 = null;
Frame.Navigate(typeof(LockView));
}
private void ResetTimer()
{
_timer2.Stop();
_timer2.Start();
ticks = 0;
}
This solution is far from perfect. I will have to use it if I can't find a better one, but there are 4 main problems with it;
It breaks the MVVM pattern. All this code has to go in the code behind of the View. I have 7 views which are accessible after the user logs in, so there will be a lot of repitition
It doesn't capture all gestures. For example is seems to ignore when scrolling up and down a listbox full of items
I have to call the ResetTimer() method or _timer2.Stop() from anywhere in the view that might be considered a gesture (even just before navigating away from the view)
It's just a messy and awkward solution
Does anyone know of a better way of achieving this? Surely there's a more elegant solution, maybe something at a higher level, rather than trying to catch every last button press and gesture.
Also, it would be useful if the app could detect whether it was running in the foreground or the background, and auto-navigates to the lock screen if the user navigates away from the app then goes back to it later.
Thanks in advance for any suggestions...

Related

drag and drop - lag in UWP

Hello drag and drop fans,
Can anyone explain why I see a long lag time when using drag and drop with my UWP apps?
I wrote a test app that contains just the drag and drop message handlers and also the pointer handlers for comparison. Here’s the code...
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
grid1.AllowDrop = true;
grid1.DragOver += Grid1_DragOver;
grid1.Drop += Grid1_Drop;
grid1.DragLeave += Grid1_DragLeave;
grid1.PointerEntered += Grid1_PointerEntered;
grid1.PointerExited += Grid1_PointerExited;
}
// Drag Handlers ************************
private void Grid1_DragOver(object sender, DragEventArgs e)
{
msgFromPointer.Text = " drag/drop item has entered";
e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Copy;
Debug.WriteLine("in grid1 drag over handler");
}
private void Grid1_DragLeave(object sender, DragEventArgs e)
{
msgFromPointer.Text = "";
}
private void Grid1_Drop(object sender, DragEventArgs e)
{
Debug.WriteLine("in grid1 drop handler");
}
// pointer handlers *******************
private void Grid1_PointerEntered(object sender, PointerRoutedEventArgs e)
{
msgFromPointer.Text = "POINTER has entered";
}
private void Grid1_PointerExited(object sender, PointerRoutedEventArgs e)
{
msgFromPointer.Text = "";
}
When doing a drag and drop to my app, there seems to be about a 1/2 second delay before my app receives the dragOver message. In comparison, the pointerOver message seems to arrive almost simultaneously with the pointer movement. The slow behavior is the same when using the touch screen or a mouse. Here’s a video of the behavior…
video of the laggy behavior
The PC I’m using has a touch screen and I’m wondering if there is some sort of touch “driver” or filter that is slowing down the drag and drop message. I've tried a bunch of Windows config settings, like mouse and display settings, but no change. The PC is a Dell Inspiron 3593, with the latest drivers. My Windows 10 version is 1903, build 18362.836
The app I’m developing uses a lot of drag and drop and this slow behavior makes the user interface really difficult. It’s kind of like trying to conduct a phone conversation with a 1/2 second delay.
Any ideas?
Dan
The DragOver event is triggered when the application determines that the element under the current pointer is a potential placement target.
This requires the pointer to hover for a period of time. This may be the reason for the delay you think.
You can try the DragEnter event, which is triggered earlier than DragOver.
Thanks

Xamarin Forms Map Viewable Area event handler

I have a Xamarin form map on my screen and I'm using PropertyChanged event to retrieve geolocation information from my server and display the proper pins on screen.
While coding the solution I noticed the PropertyChanged event is triggered multiple times (up to 10 times) with a single zoom or drag action on the map. This causes unnecessary calls to server which I want to avoid.
Ideally I want to make only one call to server when the final PropertyChanged event is called but I cant's find an easy solution to implement this.
At this point I've added a refresh button to my page that becomes enabled when a PropertyChanged event happens and I disable it after user uses the button.
Obviously this fixed the too many calls to server but made the solution manual.
I was wondering if there is a more elegant way to make the server call but do it automatically.
Thanks in advance.
I just test the PropertyChanged event on iOS side and it just triggered one time with a single zoom or drag action on the map.
While if it really triggered multiple times, you can use a timer to call the server when the final PropertyChanged event is called, for example:
public partial class MapPage : ContentPage
{
Timer aTimer;
public MapPage()
{
InitializeComponent();
customMap.PropertyChanged += CustomMap_PropertyChanged;
}
private void CustomMap_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (aTimer != null)
{
aTimer.Enabled = false;
aTimer.Stop();
aTimer.Close();
}
aTimer = new Timer();
aTimer.Interval = 1000;
aTimer.Enabled = true;
aTimer.Elapsed += ATimer_Elapsed;
aTimer.Start();
}
private void ATimer_Elapsed(object sender, ElapsedEventArgs e)
{
aTimer.Stop();
//do web request
Console.WriteLine(sender);
Console.WriteLine("CustomMap_PropertyChanged");
}
}
In the above code, I set the Interval = 1 second, that means in 1 second, whatever how many times PropertyChanged triggered, only the last call will trigger the ATimer_Elapsed function.
The Interval can be set to any value depending on your requirement.

How to Poll For Controller Input In UWP App

I'm unsure about the best practice for obtaining and updating input received from a controller monitored using the GamePad class in UWP.
I've seen a couple of examples of people using Dispatch Timers and async loops inside the GamePadAdded event. In Win32 applications, I would have handled input in the WinMain update/message loop, but in UWP apps I don't know of anything similar.
Is there a loop in UWP apps that input should be collected/handled like in Win32 apps? What is the recommended protocol for polling for input from a input device (nominally a Xbox One controller)?
I'm happy to read more about UWP app development but I'm unsure of any guides that reference something like this.
Edit: It would be productive if, instead of downvoting and moving on, you shared thoughts on why this question deserved a downvote.
I've seen a couple of examples of people using Dispatch Timers and async loops inside the GamePadAdded event
This is the right way in UWP app to read Gamepad data. A little suggestion is, move the loop reading part on UI thread if you need to update UI frequently. See the solution in this blog
Is there a loop in UWP apps that input should be collected/handled like in Win32 apps
You may make a wrapper with custom event, see the open source implementation: XBoxGamepad
public class XBoxGamepad
{
private List<Gamepad> _controllers = new List<Gamepad>();
private bool _running = true;
Task backgroundWorkTask;
public event EventHandler<GamepadButtons> OnXBoxGamepadButtonPressA;
//omitted......
public XBoxGamepad()
{
Gamepad.GamepadAdded += Gamepad_GamepadAdded;
Gamepad.GamepadRemoved += Gamepad_GamepadRemoved;
backgroundWorkTask = Task.Run(() => PollGamepad());
}
//omitted......
private void Start()
{
_running = true;
}
public void Stop()
{
_running = false;
}
public async Task PollGamepad()
{
while (true)
{
if (_running)
{
foreach (Gamepad controller in _controllers)
{
if (controller.GetCurrentReading().Buttons == GamepadButtons.A)
{
OnXBoxGamepadButtonPressA(controller, controller.GetCurrentReading().Buttons);
}
//omitted......
}
}
await Task.Delay(50);
}
}
private void Gamepad_GamepadRemoved(object sender, Gamepad e)
{
_controllers.Remove(e);
}
private void Gamepad_GamepadAdded(object sender, Gamepad e)
{
_controllers.Add(e);
}
}

User consent to stop the playing audio

Windows Phone 7.5 / Silverlight app
If user is playing music / radio on their phone and they try to launch my application, I want to give user an option to stop the currently playing option.
Working fine:
The message popup shows up fine. When I select Cancel, the popup closes, the music keeps playing and my app starts/works as normal.
Issue:
If I select Ok i.e. to stop the currently playing music on phone, the music stops but at the same time my app also exits.
Any ideas what I am doing wrong here?
Here is the code I am using. I call this method on launching:
private void CheckAudio()
{
if (FMRadio.Instance.PowerMode == RadioPowerMode.On)
{
MessageBoxResult Choice;
Choice = MessageBox.Show("For better user experience with this application it is recommended you stop other audio applications. Do you want to stop the radio?", "Radio is currently playing!", MessageBoxButton.OKCancel);
if (Choice == MessageBoxResult.OK)
{
FMRadio.Instance.PowerMode = RadioPowerMode.Off;
}
}
if (MediaPlayer.State == MediaState.Playing)
{
MessageBoxResult Choice;
Choice = MessageBox.Show("For better user experience with this application it is recommended you stop other audio/video applications. Do you want to stop the MediaPlayer?", "MediaPlayer is currently playing!", MessageBoxButton.OKCancel);
if (Choice == MessageBoxResult.OK)
{
MediaPlayer.Stop();
}
}
}
Update:
I posted my solution below. Do let me know if I am doing anything wrong.
I found the following error was being thrown:
FrameworkDispatcher.Update has not been called. Regular
FrameworkDispatcher. Update calls are necessary for fire and forget
sound effects and framework events to function correctly.
So I added this code and now it is working fine. Now upon clicking OK, the music player stops and my app launches fine. I call the SetupTimer method from InitializeComponent in App.xaml.cs
private GameTimer gameTimer;
private void SetupTimer()
{
gameTimer = new GameTimer();
gameTimer.UpdateInterval = TimeSpan.FromMilliseconds(33);
// Call FrameworkDispatcher.Update to update the XNA Framework internals.
gameTimer.Update += new EventHandler<GameTimerEventArgs>(gameTimer_Update); //delegate { try { FrameworkDispatcher.Update(); } catch { } };
// Start the GameTimer running.
gameTimer.Start();
// Prime the pump or we'll get an exception.
FrameworkDispatcher.Update();
}
void gameTimer_Update(object sender, GameTimerEventArgs e)
{
try { FrameworkDispatcher.Update(); }
catch { }
}
If anybody sees any problem/issue with the above please do let me know. Thanks.

how to disable location services in my WP7 app

I'm making a windows phone app which displays where the closest campus shuttles are (among other things). Windows Phone requires apps to allow the users to turn off location services within the app.
So, I added a toggle for it on a settings page, but it doesn't seem to do anything.
Here's the viewmodel where I declared the geocoordinatewatcher.
public MainViewModel()
{
geoWatcher = new GeoCoordinateWatcher();
if (geoWatcher.TryStart(false, TimeSpan.FromSeconds(30) )==false )
{ MessageBox.Show("The location services are disabled for this app. We can't detect the nearby stops. To turn location services back on, go to the settings page.", "Warning", MessageBoxButton.OK); }
}
private GeoCoordinateWatcher geoWatcher;
public GeoCoordinateWatcher GeoWatcher
{
get
{
return geoWatcher;
}
set
{
if (geoWatcher != value)
{
geoWatcher = value;
NotifyPropertyChanged("GeoWatcher");
}
if(geoWatcher.Status== GeoPositionStatus.Disabled)
{
geoWatcher.Stop();
}
}
}
and here's the bulk of the settings page
public SettingsPage()
{
InitializeComponent();
if (App.ViewModel.GeoWatcher.Status == GeoPositionStatus.Ready)
{
locToggle.IsChecked = true;
locToggle.Content = "On";
}
else
{
locToggle.IsChecked = false;
locToggle.Content = "Off";
}
}
private void toggleChecked(object sender, RoutedEventArgs e)
{
locToggle.Content = "On";
App.ViewModel.GeoWatcher.Start();
MessageBox.Show("this is the status " + App.ViewModel.GeoWatcher.Status.ToString(), "Info", MessageBoxButton.OK); //for debugging
}
private void toggleUnchecked(object sender, RoutedEventArgs e)
{
locToggle.Content = "Off";
App.ViewModel.GeoWatcher.Stop();
MessageBox.Show("this is the status " + App.ViewModel.GeoWatcher.Status.ToString(), "Info", MessageBoxButton.OK); //for debugging
}
When i turn the toggle off and click away from the Settings page, and go back to it, the toggle is re-enabled again.
I tried putting in a message box on the functions to debug but the status always says "Ready" and my app still uses the location services, even when I turn the toggle to "off".
Is there something I should be adding to the code so that the toggle will properly make my app stop using location services across my app if it's disabled on the settings page? Or should I be checking something else besides GeoPositionStatus? I couldn't figure out a way to make my app actually change the location services permissions or PositionStatus.
I looked at this page here, but am still confused since I followed the example at the bottom of the page, to no avail. I searched StackOverflow but I couldn't seem to find a similar question with WP. I also posted this on the AppHub forums though.
Thanks!
In your MainViewModel you need to check if they have allowed location services before you use the geocoordinatewatcher.
if(settings.LocationAllowed)
{all your code for using location}
You should probably take into account a few factors/points, most of which, you have. Anyway, you might find these helpful.
Your application settings toggle should only show when the location service is switched on on the device
GeoPositionStatus is just an Enum which contains the types of statuses.
StatusChanged is the event which is to be handled to check for changes in the device settings. See this.
You cannot change the device settings from the application.
Add event handlers before you call start on the watcher.

Resources