Introduction
In this article, I describe how to use the Windows Mobile 5 State and Notification API (SNAPI) to get notified of changes in network states. Integrating network notification is the basis to implementing background data replication. Furthermore, when an application has knowledge of available networks, it can then choose the best connection to move data between the device and a back-end server.
Background
The State and Notifications APIs provide a powerful built-in notification broker structure for the Windows Mobile 5.0 environment. Some of the requirements of SNAPI are:
- .NET Compact Framework Version 2.0
- Exposed via
Microsoft.WindowsMobile.Status
namespace
- Specific to the Windows Mobile 5.0 platform
- Included in the OS installation (not in the deployment CABs for the .NET CF 2.0) and Emulator
Using the Code
To implement application notifications, a reference to the following namespaces must be added:
Microsoft.WindowsMobile
Microsoft.WindowsMobile.Status
The following code outlines how to enable the notification callbacks within the application:
public void SetUpNotifications()
{
SystemState s;
s = new SystemState(SystemProperty.CradlePresent);
s.Changed += new ChangeEventHandler(ChangeOccurred);
stateList.Add(s);
s = new SystemState(SystemProperty.PhoneGprsCoverage);
s.Changed += new ChangeEventHandler(ChangeOccurred);
stateList.Add(s);
s = new SystemState(SystemProperty.ConnectionsNetworkCount);
s.Changed += new ChangeEventHandler(ChangeOccurred);
stateList.Add(s);
UpdateConnectionState();
}
public void ChangeOccurred(object sender, ChangeEventArgs args)
{
SystemState state = (SystemState)sender;
UpdateConnectionState();
}
public void UpdateConnectionState()
{
activesync.Checked = Convert.ToBoolean
(SystemState.GetValue(SystemProperty.CradlePresent));
gprs.Checked = Convert.ToBoolean(SystemState.GetValue
(SystemProperty.PhoneGprsCoverage));
wifi.Checked = Convert.ToBoolean(SystemState.GetValue
(SystemProperty.ConnectionsNetworkCount));
}
Timers are a useful way of using the notification APIs to help determine when to initiate replication. On a specific interval, a function can be called to initiate data movement based on network availability. The following code shows how the current state of the network can help determine which data to retrieve.
private void Sync()
{
if (activesync.Checked)
{
}
else if (wifi.Checked)
{
}
else if (gprs.Checked)
{
}
else
{
txtStatus.Text = "No Connectivity.";
return;
}
}
Conclusion
SNAPI is a excellent addition to a mobile application and can help to optimize data exchange. By adding a mobile database, an application can then be built to move data in the background to the point that users do not even realize synchronization is being executed.