Skip to content

Using SimplyMobile.Device namespace

Sami M. Kallio edited this page Oct 9, 2013 · 1 revision

SimplyMobile.Device classes are mainly static classes hiding beneath the differences of the platforms. Functionality is very C# like using properties and events to relay the data to the consumer. The design will allow clients to write reusable application logic.

The abstract classes are written so that the first client to arrive turns on the lights and the last to leave turns them off. We don't want to leave the application subscribed to system messages unnecessarily as this is a waste of resources, most importantly battery life. This brings us to the first example usage, the Battery class.

Usage of the Battery class is the same whether we are on Android, iOS or WP8 device. This example is from an Android Activity. When the activity comes active (resumes) we want to read the initial state of the battery and then subscribe to changes.

	protected override void OnResume ()
	{
		base.OnResume ();

		// Get initial level, 0-100
		this.batteryLevel.Text = Battery.Level.ToString();

		// Subscribe to level changes. 
		Battery.OnLevelChange += HandleOnLevelChange;

		// Get the initial charger connection status
		this.chargerState.Checked = Battery.Charging;

		// Subscribe to charger status changes.
		Battery.OnChargerStatusChanged += HandleOnChargerStatusChanged;
	}

To be responsible we also want to make sure we will unsubscribe when the activity stops or pauses:

	protected override void OnPause ()
	{
		base.OnPause ();
		Battery.OnLevelChange -= HandleOnLevelChange;
		Battery.OnChargerStatusChanged -= HandleOnChargerStatusChanged;
	}

Example of the first in - lights on, last out - lights off.

public static partial class Battery
{
    /// <summary>
    /// Event handler for battery level changes. 
    /// </summary>
    public static event EventHandler<EventArgs<int>> OnLevelChange
    {
        add
        {
			// if this is the first subscriber lets start the monitoring
            if (onLevelChange == null)
            {
                StartLevelMonitoring();
            }
            onLevelChange += value;
        }
        remove 
        { 
            onLevelChange -= value;
			// if this is the last client then we want to stop monitoring
            if (onLevelChange == null)
            {
                StopLevelMonitoring();
            }
        }
    }

To reuse this base code I have used partial methods to call the native portion of the code:

    /// <summary>
    /// Start level monitoring
    /// </summary>
    /// <remarks>Partial method to be implemented by platform specific provider.</remarks>
    static partial void StartLevelMonitoring();

    /// <summary>
    /// Stop level monitoring
    /// </summary>
    /// <remarks>Partial method to be implemented by platform specific provider.</remarks>
    static partial void StopLevelMonitoring();
Clone this wiki locally