Tools

Namespaces

Variants

Views

Actions

Search

Contents

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

Dynamic Lock Screen for Windows Phone 8

This article explains how to change the Lock screen image of Windows phone 8 using application that can be set in Lock screen setting. Going further, this article also explains how we can change the lock screen periodically with new image which can located on app folder or over internet. We will also see code demo for each method to set lock screen.

Introduction

Windows phone 8 has awesome features like new personalised home screen, Dynamic Lock screen, Integrated VOIP Skype etc. In Windows Phone 8, a user can choose to use an app as its lock screen background image provider. I think best feature is Dynamic Lock Screen as user first see Lock screen on his/her phone.

This article explains how to change the Lock screen image of Windows phone 8 using LockScreenManager. We will also show you how to change the Lockscreen wallpaper in background periodically using Background Agent Scheduler.

To provide the lock screen background image in the phone, we need to declare the app's intent in the app manifest file WMAppManifest.xml, and add code to handle changing the background image and then to change image periodically we need to use Windows phone Scheduler as Background Agent.

Video Demo

Here you can see the app in action changing lock screen image every 30 sec.

We are going to create this app. So let's get started! First we will show you how to set a default image to lock screen by app acting as Background image provide.

Setting up a lock screen background image

To provide the lock screen background image on Windows phone 8, first we need to update the app manifest file to declare your app as a lock screen background provider so that app can get permission to access the lock screen of the phone.

Updating the app manifest file

To Update the app manifest file so that app can access the lock screen of the phone, we need to update WMAppManifest.xml file as below.

Add the lock screen background <Extension> element in the <Extensions> element. If the <Extensions> element doesn’t appear in the file, place the entire code example below into the file. The <Extensions> element must be placed below the <Tokens> element.

Here in <Extension> element, we need to define ExtensionName, ConsumerID and TaskID. In your application, you can use same ConsumerID and TaskID as below.

Now users can see the app in the Lock Screen Settings and choose to let the app change the lock screen.

DefaultLockScreen.jpg

Once, User set our app as default lock screen provide in setting, our default image is set as lock screen as our app service agent is not yet got chance to set image dynamically.So for this reason, we should include a default lock screen background image at the root of your main project's XAP package. Name the image DefaultLockScreen.jpg.

Size of the Lock screen image

Recommended image size for lock screen is 480px X 800px or 960px X 1708px but if provided image is too big than it will be automatically cropped from center and set in lock screen. Also if provided image is too small than it will be re-sized to big automatically but it will be blurred/scratched and look odd.

Adding code to change the Lock screen background

We can change background of Lock screen using Windows.Phone.System.UserProfile.LockScreenManager namespace. To change the background, our app must have selected as Lock screen background provider in Lockscreen setting, to check that Go to Setting -> Lock Screen.

if(!LockScreenManager.IsProvidedByCurrentApplication){// If you're not the provider, this call will prompt the user for permission.// Calling RequestAccessAsync from a background agent is not allowed. await LockScreenManager.RequestAccessAsync();}

// Only do further work if the access is granted.if(LockScreenManager.IsProvidedByCurrentApplication){// change the background here. }

This code ask user to give permission to our app to access lock screen. Once user click on Yes, our app is granted to change the lock screen and become current Lock screen image provider.

Then, we need to call the LockScreen.SetImageUri method with the URI of the picture. The URI must be prefixed by ms-appx:/// if the picture is stored in the resources, or ms-appdata:///Local/ if the picture is stored in root folder.

ms-appx:/// for resources bundled within the .xap

ms-appdata:///local/ for local images within the root folder.

We can not set image located on server using Image URL directly on LockScreen.SetImageUri method. But we do it by downloading image using WebClient and storing it on IsolatedStorage and then can use above ms-appx:/// on LockScreen.SetImageUri method.

The following final code example shows how we can change the lock screen background image. We need to call below function. Here method uses async as 'the user for permission can only be done by using an async call.

private async void LockScreenChange(string filePathOfTheImage, bool isAppResource){if(!LockScreenManager.IsProvidedByCurrentApplication){// If you're not the provider, this call will prompt the user for permission.// Calling RequestAccessAsync from a background agent is not allowed. await LockScreenManager.RequestAccessAsync();}

// Only do further work if the access is granted.if(LockScreenManager.IsProvidedByCurrentApplication){// At this stage, the app is the active lock screen background provider.// The following code example shows the new URI schema.// ms-appdata points to the root of the local app data folder.// ms-appx points to the Local app install folder, to reference resources bundled in the XAP packagevar schema = isAppResource ?"ms-appx:///":"ms-appdata:///Local/";var uri =new Uri(schema + filePathOfTheImage, UriKind.Absolute);

// Set the lock screen background image. LockScreen.SetImageUri(uri);

// Get the URI of the lock screen background image.var currentImage = LockScreen.GetImageUri();System.Diagnostics.Debug.WriteLine("The new lock screen background image is set to {0}", currentImage.ToString()); MessageBox.Show("Lock screen changed. Click F12 or go to lock screen.");}else{ MessageBox.Show("Background cant be updated as you clicked no!!");}}

Once you say Yes, This app becomes current background image provider of Lock screen and we can see the image set by above method in lock screen by pressing F12 during using in Windows Phone 8 Emulator.

Image set on Lock screen

Home page

To set lock screen image, call LockScreenChange method as below. Here we need to pass Image file path that we want to set as Lock screen and whether it is in app resources folder or in root.

LockScreenChange("wallpaper/CustomizedPersonalWalleper_0.jpg", true);

You can see new lock screen image in below image.

New Lock Screen Image

Linking to the lock screen settings screen from within your app

We can’t programmatically turn off our app as a lock screen background image provider from within the app. The user will need to visit the phone's settings screen and make the change themselves. Providing a link to the settings screen makes this useful and easy for user.
The following code example shows you how you can route a button click to the phone's lock screen settings screen using URI of setting page in Windows Phone 8 .

So we have shown above how to set image as lock screen and for that we need to in our project so that our app work as lock image provide. Now Question is where image should located that we are going to set to lock screen.

There are 3 option for image location.

Image located on app folder

Image located on internet on specific image URL

Image coming from RSS

1) Dynamic Lock screen with images located on app folder

We saw above how we can change the lock screen image. Now We want to make app that change the lock screen periodically using images located on app folder. To change the lock screen after some period, we need to use Windows Phone Scheduled Task Agent', also known as Background Agent.

Change Lock screen image Dynamically using Background Agent

First we need to add Scheduled Task Agent to our solution from "New Project" as seen below. To do that go to New Project -> Windows Phone Scheduled Task Agent.

Windows Phone Scheduled Task Agent

In MainPage.xaml.cs class, we need to add PeriodicTask type ScheduleAgentTask as shown below which run after some time (normally after 30 min). But to test this in simulator we cant wait 30 min, so we have made it to run after every 30 sec using LaunchForTest(String, TimeSpan) method which run only on device/simulator when application is in debug mode. You can see we have defined #define DEBUG_AGENT before calling LaunchForTest(String, TimeSpan) method.

Here we also defined ExpirationTime of this PeriodicTask by periodicTask.ExpirationTime to 14 days or less from the current date. The default value is 14 days from the current date. Applications that use ScheduledTask must renew their schedule at least once every two weeks by calling Remove(String) and then Add(ScheduledAction) to add the task when the main application is running in the foreground. This helps to ensure that unused applications are not draining device resources.

Note: The LaunchForTest(String, TimeSpan) method is provided so that you can run your agent on a more frequent schedule than it will run on an actual device. This method is only for application development. It will not function except for in applications that are deployed using the development tools. You should remove calls to this method from your production application. In this example, the call is placed in an #if block to enable you to easily switch between debugging and production functionality. To enable the call, put the following line at the top of the ScheduledAgent.cs file. #define DEBUG_AGENT

}catch(InvalidOperationException exception){if(exception.Message.Contains("BNS Error: The action is disabled")){// load error text from localized strings MessageBox.Show("Background agents for this application have been disabled by the user.");}if(exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added.")){// No user action required. The system prompts the user when the hard limit of periodic tasks has been reached.}}catch(SchedulerServiceException){// No user action required.}}

In ScheduledTaskAgent1 Project, ScheduledAgent.cs file, in OnInvoke(ScheduledTask) method which call periodically we need to write code that change the lock screen image periodically. We want to set 10 image one by one periodically in this sample application.

We have 10 images in wallpaper folder. Each images name is start with CustomizedPersonalWalleper_ and ends with image number(0 to 9). Here we first check which image is currently set as lock screen by LockScreen.GetImageUri method.

// Get the URI of the lock screen background image.var currentImage = LockScreen.GetImageUri();

Then we find image number from it by using Substring and String.IndexOf method as below and create the image name that we want to set next and pass it to LockScreenChange method. So logic becomes as shown in code below.

// If debugging is enabled, launch the agent again in one minute.// debug, so run in every 30 secs#if(DEBUG_AGENT) ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));System.Diagnostics.Debug.WriteLine("Periodic task is started again: "+ task.Name);#endif

// Call NotifyComplete to let the system know the agent is done working. NotifyComplete();}

Setting image that located on internet as Lock screen directly using image url path to LockScreen.SetImageUri() is not possible currently. So how we can set image which located over internet. There is one way to do that by downloading image on IsolatedStorage and then using LockScreen.SetImageUri() we can set image as Lock Screen.

Below we will see how to download image from internet and store it in IsolatedStorage and then how to set that image as Lock screen.

You can see below in screenshot that a image located over internet is now set as Lock screen.

Dynamic Lock screen image like Bing App

We need to upload different image over internet periodically in other platform so that our app in Windows Phone 8 can download it and set it as Lock screen image. To Upload image periodically over internet in other platform, We can create some Windows Service in .net that will run on Windows and upload images to a specific URL over internet by picking image from provided folder path. OR we can have bunch of image URL to set as lock screen periodically.

Concept becomes Reality

Below concept can now become reality. To make it real, We need to have one image URL path which will have different images periodically with some details written on image and our lock screen app will download image from that Image URL path and set as Lock screen.
We just need to upload different images to specific image URL path. To upload image, we can use Windows Service of other platform or we can upload it manually.

We can not write text over image at runtime in Windows Phone 7 and 8 but we can do that in other platform using imaging API for example in .net and upload composed image to specific Image URL and our lock screen app in windows phone 8 will set it as lock screen.

So this way, below concept becomes real app.

3) Dynamic Lock screen with images coming from RSS

Here we will see how to set image from RSS as lock screen in windows phone 8. To do this, RSS must have image URL in it. To set lock screen image from RSS, first we need to download image from RSS using image URL shown in RSS. So first we need to parse the RSS and checking for each image with type .jpeg or .png and then download image from it and set it to lock screen.

We also need to consider the structure of the RSS while downloading image from it as we need to parse RSS according to RSS structure and image URL location in RSS.

Sample RSS

Here is the sample RSS which contains Image URL in it. We get this RSS from this RSS link.

As you can see in above code, we first parse the RSS, get all the images URLs from that RSS and store Image URLs in global string array imgarray. So that we can use that string array imgarray in other methods and can get the image URL we have retrieved from given RSS.

Download RSS images

Now after getting all image URLs from RSS, we need to download those images one by one and store it in IsolatedStorage as we can not use image url during setting image using method DownloadImagefromServer(string imageUrl). So that's why we need to download images first and store it in IsolatedStorage. We have done that in below code in method DownloadImagefromServer(string imageUrl) which called in above Event handler myRSS_DownloadStringCompleted.

As you can see above in client_OpenReadCompleted event handler, we are downloading other remaining images from imgarray by calling DownloadImagefromServer(string imageUrl) method.

Set Lock screen with RSS Images

After downloading all Images from RSS to IsolatedStorage with specific name, we need to set it all to lock screen using LockScreen.SetImageUri(uri) method periodically by Background Agent Scheduler.

private async void LockScreenChange(string filePathOfTheImage, bool isAppResource){if(!LockScreenManager.IsProvidedByCurrentApplication){// If you're not the provider, this call will prompt the user for permission.// Calling RequestAccessAsync from a background agent is not allowed. await LockScreenManager.RequestAccessAsync();}

// Only do further work if the access is granted.if(LockScreenManager.IsProvidedByCurrentApplication){// At this stage, the app is the active lock screen background provider.// The following code example shows the new URI schema.// ms-appdata points to the root of the local app data folder.// ms-appx points to the Local app install folder, to reference resources bundled in the XAP packagevar schema = isAppResource ?"ms-appx:///":"ms-appdata:///Local/";var uri =new Uri(schema + filePathOfTheImage, UriKind.Absolute);

// Set the lock screen background image. LockScreen.SetImageUri(uri);

// Get the URI of the lock screen background image.var currentImage = LockScreen.GetImageUri();System.Diagnostics.Debug.WriteLine("The new lock screen background image is set to {0}", currentImage.ToString()); MessageBox.Show("Lock screen changed. Click F12 or go to lock screen.");}else{ MessageBox.Show("Background cant be updated as you clicked no!!");}}

Change lock screen periodically with RSS Images

Below is the code to change the lock screen with RSS images periodically.

In ScheduledTaskAgent1 project, ScheduledAgent.cs class, in OnInvoke(ScheduledTask task) Method, we need to write code as shown below. Here we are just downloading 25 images from given RSS. as we know that that RSS will have only 25 images in it.

// If debugging is enabled, launch the agent again in one minute.// debug, so run in every 30 secs#if(DEBUG_AGENT) ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));System.Diagnostics.Debug.WriteLine("Periodic task is started again: "+ task.Name);#endif

// Call NotifyComplete to let the system know the agent is done working. NotifyComplete();}

DEMO APP: Flicker RSS Dynamic Lock Screen Application

I have also written a article for Flicker RSS Dynamic Lock Screen Application which set lock screen periodically with images from Flicker RSS and also images which user asked for. Please find that article and source code of app on below link.
Flicker RSS Dynamic Lock Screen

Summary

So this way, we can create application for Windows Phone 8 that change the lock screen background periodically. We can also set image which located on server as lock screen. This image located over internet server might have some information written on it as text or image.

So we have seen how to create set a image as lock screen, how to make lock screen image dynamic with images located on app folder or over internet.

Source code

You can find the running source code of all demo applications presented in this article on below links.