In this article I will talk about how to detect Windows Phone is locking or incoming phone calls or Alarm is going to ring, etc. The similarities among all these actions are shell crome covers the frame of Windows Phone (Some UI covers the screen).
Microsoft.Phone.Controls has Obscured event is triggered whenever shell crome covers the frame of Windows Phone.
If you are making any FM player, it should stop playing in case of incoming phone call or alarms or on locking of screen.
It should resume playing when phone call ends, when alarms is dismissed or on unlocking of screen.
Obscured and Unobscured event can be used in such scenarios.
Let's write small code:
Step 1: Create a Silverlight for Windows Phone project.
Step 2: Add two textboxes inside contentpanel of MainPage.xaml
<TextBlock Name="txtObs" Grid.Column="0" Margin="0,10,0,0" Grid.Row="2"/>
<TextBlock Name="txtUnobs" Grid.Column="0" Margin="0,80,0,0" Grid.Row="2"/>
Step 3: Add below lines of code in the constructor of the MainPage.xaml.cs. Create instance of RootFrame and add Obscured and Unobscured event to it.
PhoneApplicationFrame rootFrame = (Application.Current as App).RootFrame;
rootFrame.Obscured += OnObscured;
rootFrame.Unobscured += Unobscured;
Step 4: Add OnObscured method and Unobscured method. For example OnObscured method will be triggered when phone is getting locked and Unobscured event will be triggered when phone is getting unlocked.
void OnObscured(Object sender, ObscuredEventArgs e)
txtObs.Text = "Obscured at " + DateTime.Now.ToString();
void Unobscured(Object sender, EventArgs e)
txtUnobs.Text = "Unobscured at " + DateTime.Now.ToString();
Step 5: Now run the application and lock and unlock the screen you will notice. Timestamp of Onbscured is when screen is locked and Timestamp of Unobscured is when screen is unlocked.
This can be tested only on device.
Points to remember:
1. Use Obscured event when you want your application to do something in background even if phone is locked or even when incoming phone call.
2. Make sure when you are using Obscured event to do some task in background, it should use minimal CPU or battery consumption.
3. The end user should be prompted the user for confirmation to run something on background.
4. To run your application in locked mode ApplicationIdleDetectionMode needs to be disabled.
PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;
Once ApplicationIdleDetectionMode is disable can be enabled by restart of the Application.
This ends the article on usage of Obscured and Unobscured event in Windows Phone.