Monday, December 2, 2013

Quick! - How to Open WP Settings from Code

The Windows Phone File and Uri associations are very useful for implementing custom cross-app functionality like Pictures Lab and other apps provide. Windows Phone also provides uri schemes for many built-in apps and settings which can be very handy.
The Windows Phone 8 update GDR3 introduced a new setting to lock the screen rotation. This setting is quite useful especially when reading in bed or for providing on-screen QR codes to scanners.
This useful screen rotation lock is unfortunately hidden in the settings and it takes a few taps to access it. Therefore I've written a tiny free app called Screen Rotation Lock. It provides quick access to the screen rotation settings through a pinned secondary tile.



The relevant code in the MainPage is rather straight forward but there are some details which are worth sharing and which apply to any shortcut uri navigation:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
   base.OnNavigatedTo(e);

   // Actual shortcut navigation?
   if (NavigationContext.QueryString.ContainsKey(UriQueryStringKeyPage))
   {
      // If coming from setting than skip here
      if (e.NavigationMode == NavigationMode.Back)
      {
         Application.Current.Terminate();
      }
      // Otherwise go to setting
      Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-screenrotation:"));
   }

   //Check for support
   var gdr3Version = new Version(8, 0, 10492);
   if (Environment.OSVersion.Version < gdr3Version)
   {
      MessageBox.Show(String.Format("Sorry, your phone does not support the screen rotation lock feature yet. You need to have the Windows Phone version {0} installed  (WP 8 GDR 3).\r\nThe app will now exit.", gdr3Version), "Not supported version", MessageBoxButton.OK);
      Application.Current.Terminate();
   }
}

The first if statement tests if the navigation comes from the secondary tile with the associated key UriQueryStringKeyPage. If it's a back navigation, the user was actually forwarded already to the setting and tapped back. In that case we don't want the user to land in our app, but rather go back to the start screen where she/he comes from, so we close our app. If it's not a back navigation the forward to the setting takes place using the Launcher API and the LaunchUriAsync method with the right uri for screen rotation.
The last if statement tests the version of the device and shows an error message if the device does not have GDR3 installed. This is done as last statement since it's actually only needed when the user wants to pin the secondary tile shortcut and opens the app itself.

No comments:

Post a Comment