×
Namespaces

Variants
Actions
(Difference between revisions)

Dynamic Lock Screen for Windows Phone 8

From Nokia Developer Wiki
Jump to: navigation, search
chintandave_er (Talk | contribs)
(Chintandave er -)
chintandave_er (Talk | contribs)
(Chintandave er - added ref. links)
Line 1: Line 1:
 
[[Category:Windows Phone]][[Category:Windows Phone 8]][[Category:Silverlight]][[Category:Code Examples]]
 
[[Category:Windows Phone]][[Category:Windows Phone 8]][[Category:Silverlight]][[Category:Code Examples]]
 
{{Abstract|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. }}
 
{{Abstract|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. }}
 
 
{{Note|This is a community entry in the [[Windows Phone 8 Wiki Competition 2012Q4]].}}
 
{{Note|This is a community entry in the [[Windows Phone 8 Wiki Competition 2012Q4]].}}
 
 
{{ArticleMetaData <!-- v1.2 -->
 
{{ArticleMetaData <!-- v1.2 -->
 
|sourcecode= [[Media:DynamicLockScreen.zip]]
 
|sourcecode= [[Media:DynamicLockScreen.zip]]
Line 87: Line 85:
 
</code>
 
</code>
  
This code ask user to give permission for the app to provide wallpaper images to the lock screen. Once user click on '''OK''', our app is granted to change the lock screen and become current Lock screen image provider.
+
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.
  
 
[[File:AppAsk DL.png|300x480px]]
 
[[File:AppAsk DL.png|300x480px]]
  
Then, we need to call the [http://msdn.microsoft.com/en-us/library/windowsphone/develop/windows.phone.system.userprofile.lockscreen.setimageuri 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.
+
Then, we need to call the [http://msdn.microsoft.com/en-us/library/windowsphone/develop/windows.phone.system.userprofile.lockscreen.setimageuri 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.
  
* "ms-appx:///" for resources bundled within the xap
 
* "ms-appdata:///local/" for local images within the root folder.
 
  
 
The following final code example shows how we can change the lock screen background image. We need to call below function. Here method uses {{Icode|async}} as 'the user for permission can only be done by using an {{Icode|async}} call.
 
The following final code example shows how we can change the lock screen background image. We need to call below function. Here method uses {{Icode|async}} as 'the user for permission can only be done by using an {{Icode|async}} call.
Line 133: Line 132:
 
</code>
 
</code>
  
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 WP8 Simulator.  
+
 
 +
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.  
  
 
<gallery widths="300px" heights="480px">
 
<gallery widths="300px" heights="480px">
Line 145: Line 145:
 
  LockScreenChange("wallpaper/CustomizedPersonalWalleper_0.jpg", true);
 
  LockScreenChange("wallpaper/CustomizedPersonalWalleper_0.jpg", true);
 
</code>
 
</code>
 +
  
 
You can see new lock screen image in below image.  
 
You can see new lock screen image in below image.  
Line 153: Line 154:
  
 
== Dynamic Lock screen ==
 
== Dynamic Lock screen ==
We saw above how we can change the lock screen image. Now We want to make app that change the lock screen periodically like in built 'Bing' app of Windows Phone 8. To change the lock screen after some period, we need to use '''Windows Phone Scheduled Task Agent''', also known as '''Background Agent'''.
+
We saw above how we can change the lock screen image. Now We want to make app that change the lock screen periodically like in built 'Bing' app of Windows Phone 8. To change the lock screen after some period, we need to use [http://bit.ly/T5J4Wy Windows Phone Scheduled Task Agent]', also known as [http://bit.ly/T5J4Wy Background Agent].
  
 
=== Change Lock screen image Dynamically using Background Agent ===
 
=== Change Lock screen image Dynamically using Background Agent ===
Line 222: Line 223:
 
In '''ScheduledTaskAgent1''' Project, '''ScheduledAgent.cs''' file, in [http://msdn.microsoft.com/en-us/library/microsoft.phone.scheduler.scheduledtaskagent.oninvoke(v=vs.92).aspx 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.  
 
In '''ScheduledTaskAgent1''' Project, '''ScheduledAgent.cs''' file, in [http://msdn.microsoft.com/en-us/library/microsoft.phone.scheduler.scheduledtaskagent.oninvoke(v=vs.92).aspx 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 {{Icode|GetImageUri()}} method.
+
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 [http://msdn.microsoft.com/en-us/library/windowsphone/develop/windows.phone.system.userprofile.lockscreen.getimageuri(v=vs.105).aspx LockScreen.GetImageUri] method.
  
 
<code csharp>
 
<code csharp>
Line 229: Line 230:
 
</code>
 
</code>
  
Then we find image number from it by using {{Icode|Substring}} and {{Icode|IndexOf}} method as below and create the image name that we want to set next and pass it to {{Icode|LockScreenChange}} method. So the logic becomes as shown in code below.
+
 
 +
Then we find image number from it by using [http://msdn.microsoft.com/en-us/library/ms187748.aspx Substring] and [http://msdn.microsoft.com/en-us/library/system.string.indexof.aspx String.IndexOf] method as below and create the image name that we want to set next and pass it to {{Icode|LockScreenChange}} method. So logic becomes as shown in code below.
 +
 
 
<code csharp>
 
<code csharp>
 
string imgCount = currentImage.ToString().Substring(currentImage.ToString().IndexOf('_') + 1, currentImage.ToString().Length - (currentImage.ToString().IndexOf('_') + 1)).Replace(".jpg", "");
 
string imgCount = currentImage.ToString().Substring(currentImage.ToString().IndexOf('_') + 1, currentImage.ToString().Length - (currentImage.ToString().IndexOf('_') + 1)).Replace(".jpg", "");
Line 242: Line 245:
  
 
=== ScheduledAgent.cs ===  
 
=== ScheduledAgent.cs ===  
So Final code of OnInvoke Method is as below.
+
So Final code of [http://msdn.microsoft.com/en-us/library/microsoft.phone.scheduler.scheduledtaskagent.oninvoke(v=vs.92).aspx OnInvoke(ScheduledTask)] Method is as below.
 
<code csharp>
 
<code csharp>
 
protected override void OnInvoke(ScheduledTask task)
 
protected override void OnInvoke(ScheduledTask task)

Revision as of 10:09, 16 November 2012

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.

Note.pngNote: This is a community entry in the Windows Phone 8 Wiki Competition 2012Q4.

WP Metro Icon File.png
WP Metro Icon UI.png
WP Metro Icon Web.png
SignpostIcon XAML 40.png
WP Metro Icon WP8.png
Article Metadata
Code ExampleTested with
Devices(s): Windows Phone 8 device, Nokia Lumia 920, 820
Compatibility
Platform(s): Windows Phone 8
Windows Phone 8
Device(s): Windows Phone 8 Only
Article
Keywords: LockScreenManager, Background Agent
Created: chintandave_er (06 Nov 2012)
Last edited: chintandave_er (16 Nov 2012)

Contents

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 default 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.

  1. In Solution Explorer, expand Properties, right-click WMAppManifest.xml, click Open With, and then click Source Code (Text Editor) With Encoding.
  2. 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.


<Extensions>
<Extension ExtensionName="LockScreen_Background" ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default" />
</Extensions>

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

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.

Setting DL.png

To check that whether our app is selected as Lock screen image provider or not through code, we can use LockScreenManager.IsProvidedByCurrentApplication method. And if it return false, we use LockScreenManager.RequestAccessAsync() method to ask user to select our app as Provider.

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.

AppAsk DL.png

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.


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 package
var 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.

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.

Dynamic Lock screen

We saw above how we can change the lock screen image. Now We want to make app that change the lock screen periodically like in built 'Bing' app of Windows Phone 8. 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.

In MainPage.xaml.cs class, we need to add PeriodicTask type ScheduleAgentTask as shown below which run after some time. To test this in simulator, we have made it to run after every 30 sec using LaunchForTest(String, TimeSpan) method.

Note.pngNote: 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

Here is the Method which add our PeriodicTask to ScheduledActionService as shown below.

private void StartPeriodicAgent()
{
// is old task running, remove it
periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;
if (periodicTask != null)
{
try
{
ScheduledActionService.Remove(periodicTaskName);
}
catch (Exception)
{
}
}
// create a new task
periodicTask = new PeriodicTask(periodicTaskName);
// load description from localized strings
periodicTask.Description = "This is Lockscreen image provider app.";
// set expiration days
periodicTask.ExpirationTime = DateTime.Now.AddDays(14);
try
{
// add this to scheduled action service
ScheduledActionService.Add(periodicTask);
// debug, so run in every 30 secs
#if(DEBUG_AGENT)
ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(30));
System.Diagnostics.Debug.WriteLine("Periodic task is started: " + periodicTaskName);
#endif
 
}
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.

string imgCount = currentImage.ToString().Substring(currentImage.ToString().IndexOf('_') + 1, currentImage.ToString().Length - (currentImage.ToString().IndexOf('_') + 1)).Replace(".jpg", "");
 
if (imgCount != "9")
Imagename = "wallpaper/CustomizedPersonalWalleper_" + Convert.ToString(Convert.ToUInt32(imgCount) + 1) + ".jpg";
else
Imagename = "wallpaper/CustomizedPersonalWalleper_0.jpg";
 
LockScreenChange(Imagename, true);

ScheduledAgent.cs

So Final code of OnInvoke(ScheduledTask) Method is as below.

protected override void OnInvoke(ScheduledTask task)
{
 
// Get the URI of the lock screen background image.
var currentImage = LockScreen.GetImageUri();
string Imagename = string.Empty;
 
string imgCount = currentImage.ToString().Substring(currentImage.ToString().IndexOf('_') + 1, currentImage.ToString().Length - (currentImage.ToString().IndexOf('_') + 1)).Replace(".jpg", "");
 
if (imgCount != "9")
Imagename = "wallpaper/CustomizedPersonalWalleper_" + Convert.ToString(Convert.ToUInt32(imgCount) + 1) + ".jpg";
else
Imagename = "wallpaper/CustomizedPersonalWalleper_0.jpg";
 
LockScreenChange(Imagename, true);
 
// 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();
}

Summary

So this way, we can create application for Windows Phone 8 that change the lock screen background periodically. We can also create image run-time or add some text to image run-time to make this application more useful. Here we took only 10 image to set as lock screen periodically, but we can increase number of images.

Source code

You can find the source code of this application here File:DynamicLockScreen.zip

2867 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×