24 June 2014

Messaging class for detecting and broadcasting that your Universal app is running in the background

Some time ago I discovered that you can trap Window.Current.VisibilityChanged in a Windows 8 app to check if the app was running in the background, and that you can use that moment to pause a game and/or save the state to storage. The fun thing is, this now works in Universal apps too, that is – and thus, also on Windows Phone 8.1.Although we can discuss if  the app is really running in the background or that is actually being suspended when it runs on Windows Phone – the mechanism is the same and it can be used to the same end.

So make this more easy to use, I made this very simple class, based upon the MVVMLight MessageBase class:

using Windows.UI.Xaml;
using GalaSoft.MvvmLight.Messaging;

namespace WpWinNl.Messages
{
  public class WindowVisibilityMessage : MessageBase
  {
    public WindowVisibilityMessage(bool visible, object sender = null, 
object target = null) :base(sender, target) { Visible = visible; } public bool Visible { get; protected set; } public static void Setup() { Window.Current.VisibilityChanged += (s, f) => Messenger.Default.Send(new WindowVisibilityMessage(f.Visible)); } } }

and all you have to use it, is to simply put

protected override void OnLaunched(LaunchActivatedEventArgs e)
{
   WindowVisibilityMessage.Setup();
   //Rest of code omitted
 

in the first line of OnLaunched in the App.Xaml.cs

Now anywhere in your app you can now listen for the WindowVisibilityMessage to come by and act on it, like this:

Messenger.Default.Register<WindowVisibilityMessage>(this, p =>
{
  if (p.Visible)
  {
    //do something 
  }
  else
  {
    //do something else
  }
});

And that’s all. The source of this class is already on codeplex and it’s also in the full WpWinNl NuGet package that I released yesterday. Since this class and it’s use is prettysimple and straightforward, I am going to skip a sample solution. A more comprehensive sample where this class plays a minor supporting role is coming soon

No comments: