We all know that in its current state the WP7 does not allow for 3rd party developers to create applications which run in the background (which is going to change in a new OS release see here). However even though they do not allow your application to run in the back ground there is a way you can allow your application to continue to run if the phone is not in use or if the lock screen has come down. For details on this you can read this MSDN article.
In this post we will walk though the code needed to handle the idle detection as well as a few talking points on what you need to do in order for your application to be a ‘good citizen’.
How to make your app be a good citizen?
- Do NOT do this by default, there must be some very compelling reasons to do this
- Only disable the idle in the parts of your application which this makes sense (ie long data entry screens, movies, audio, etc)
- Make sure to give your user a way to disable this in case they do not want/like this ability. I would suggest doing this on a settings screen.
- Make sure you stop all background processes in your application when you notice the obscured event (more on that below) in order to help preserve battery life.
How to enable running under lock/while idle?
Setting up to handle the Obscured and Unobscured Events -- App.xaml.cs
public App()
{
// Bunch of other stuff in the App() method which is not needed for this example
RootFrame.Obscured += Obscured;
RootFrame.Unobscured += Unobscured;
}
private void Unobscured( object sender, EventArgs e )
{
// turn on items like location services which may have been turned off
}
private void Obscured( object sender, ObscuredEventArgs e )
{
// turn off items like location services, background threads, etc
}
Creating a User Settings class to store this setting in order to allow the user to disable this
public class UserSettings
{
///
/// This setting is used to determine if the user has allowed us to run our appplication
/// while the lock screen is down. This will remove the need for some tombstoning.
///
private bool _allowApplicationToRunWhileLocked = true;
public bool AllowApplicationToRunWhileLocked
{
get { return _allowApplicationToRunWhileLocked; }
set { _allowApplicationToRunWhileLocked = value; }
}
}
Making the call to disable the setting based on the User Setting
if ( cachedUserSettings.AllowApplicationToRunWhileLocked )
{
// this is where the magic happens
PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;
}
As you can see enabling your application disable the idle and run under the lock screen is very, very easy. However like everything else on mobile devices this will lower the batter performance and this should ONLY be done as needed.
Till next time,
Posted
02-15-2011 5:34 AM
by
Derik Whittaker