Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 42 ยท Platform Features

Connectivity, Location and Device Sensors

Use .NET MAUI Essentials to read network state, get GPS location, listen to the accelerometer, battery and haptics, and learn the patterns for sensor events.

Phones are packed with hardware, and .NET MAUI wraps the common pieces in a set of small static APIs called Essentials. You do not write Android or iOS code to ask whether the device is online, where it is, how charged the battery is, or whether the user shook it. This lesson covers the most useful ones and teaches the event patterns that apply to all of them.

Sensors are not available in the in-browser runner. MAUI code is shown read-only. The runnable examples are C# stand-ins that simulate readings so you can practice the logic around sensors, which is where most bugs live.

Network connectivity

Connectivity.Current tells you if the device has internet access and what kind of connection it uses:

C#
NetworkAccess access = Connectivity.Current.NetworkAccess;

if (access == NetworkAccess.Internet)
{
    // safe to call the server
}

IEnumerable<ConnectionProfile> profiles = Connectivity.Current.ConnectionProfiles;
bool onWifi = profiles.Contains(ConnectionProfile.WiFi);

NetworkAccess has Internet, ConstrainedInternet (for example a captive portal), Local, None and Unknown. A value of Internet does not guarantee your server is reachable, so you must still handle failed requests, as covered in consuming REST APIs.

Listen for changes with an event. Always unsubscribe when the page goes away:

C#
protected override void OnAppearing()
{
    base.OnAppearing();
    Connectivity.Current.ConnectivityChanged += OnConnectivityChanged;
}

protected override void OnDisappearing()
{
    Connectivity.Current.ConnectivityChanged -= OnConnectivityChanged;
    base.OnDisappearing();
}

void OnConnectivityChanged(object? sender, ConnectivityChangedEventArgs e)
{
    OfflineBanner.IsVisible = e.NetworkAccess != NetworkAccess.Internet;
}

Geolocation

Add the location permission first (see Permissions), then:

C#
var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10));

Location? location = await Geolocation.Default.GetLocationAsync(request);

if (location is not null)
{
    Console.WriteLine($"{location.Latitude}, {location.Longitude}");
}

GetLastKnownLocationAsync() returns the cached position immediately and is perfect for a quick first paint. Both can return null. They can throw FeatureNotSupportedException, FeatureNotEnabledException (location switched off) or PermissionException, so wrap the call in try/catch.

The Location class also calculates distances:

C#
double km = Location.CalculateDistance(here, there, DistanceUnits.Kilometers);

For continuous tracking use Geolocation.Default.StartListeningForegroundAsync(...) and the LocationChanged event, and stop when you no longer need it. GPS is one of the biggest battery drains.

Sensors: the shared pattern

Every sensor class follows the same shape:

Step Accelerometer example
Check support Accelerometer.Default.IsSupported
Subscribe Accelerometer.Default.ReadingChanged += OnReading;
Start Accelerometer.Default.Start(SensorSpeed.UI);
Stop Accelerometer.Default.Stop();

SensorSpeed is Default, UI, Game or Fastest. Faster means more readings per second and more battery use. The same pattern works for Gyroscope, Magnetometer, Compass, Barometer and OrientationSensor.

C#
void StartShakeDetection()
{
    if (!Accelerometer.Default.IsSupported) return;
    Accelerometer.Default.ReadingChanged += OnReading;
    Accelerometer.Default.Start(SensorSpeed.UI);
}

void OnReading(object? sender, AccelerometerChangedEventArgs e)
{
    Vector3 a = e.Reading.Acceleration;   // in g, includes gravity (about 1 g at rest)
    // ...
}

Sensor events arrive on a background thread. If you touch the UI, switch to the main thread with MainThread.BeginInvokeOnMainThread(...).

Battery, vibration and haptics

C#
double level = Battery.Default.ChargeLevel;           // 0.0 to 1.0
BatteryState state = Battery.Default.State;           // Charging, Discharging, Full, ...
EnergySaverStatus saver = Battery.Default.EnergySaverStatus;

Vibration.Default.Vibrate(TimeSpan.FromMilliseconds(200));
HapticFeedback.Default.Perform(HapticFeedbackType.Click);
Flashlight.Default.TurnOnAsync();   // needs camera/flashlight permission on some platforms

Prefer HapticFeedback for small confirmations (a toggle, a snap), and keep Vibration for alerts. Respect energy saver mode by reducing work, such as stopping polling.

Try it: a simulated connectivity monitor

Real connectivity events arrive from the OS. Here an event source is simulated so you can see how a view model should react, including the flapping connection that causes banner flicker.

C# Stand-in: connectivity events with a debounce

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A state only reaches the banner if it stays stable for the debounce time. The one-hundred-millisecond flap at 1000 ms never shows. In MAUI the source would be Connectivity.Current.ConnectivityChanged.

Try it: shake detection from accelerometer readings

A real accelerometer reports three values many times per second. Detecting a shake means measuring how strong the acceleration is and ignoring gravity and tiny jitters.

C# Stand-in: shake detection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Subtracting 1 g removes gravity. Requiring several hits in a row filters out accidental bumps. In MAUI you would call Add from ReadingChanged, using e.Reading.Acceleration.

Good habits for sensors and network code

  • Check IsSupported and handle exceptions: simulators and emulators often lack hardware.
  • Start sensors in OnAppearing, stop in OnDisappearing, and unsubscribe from every event.
  • Ask for the lowest accuracy and slowest speed that does the job.
  • Debounce events, as above, so the UI does not flicker.
  • Test the offline path on purpose. Turn on airplane mode in the emulator.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which NetworkAccess value means the device has some connection but not to the internet?

    Local means a network connection exists (for example a LAN) without verified internet access.
  2. 2. Why must you unsubscribe from ConnectivityChanged in OnDisappearing?

    The event source is static, so it keeps your page alive and keeps calling it unless you unsubscribe.
  3. 3. What does SensorSpeed.Fastest trade off?

    Faster sensor rates deliver more readings but cost more battery and CPU.
  4. 4. An accelerometer reading at rest shows roughly what total magnitude?

    Gravity is always included, so the vector length at rest is about 1 g.

Summary

  • Connectivity, Geolocation, Accelerometer, Battery and Vibration are static Essentials APIs.
  • Sensors share one pattern: check support, subscribe, start, stop.
  • Events may arrive off the UI thread, so marshal to MainThread.
  • Debounce and filter raw readings, and always handle exceptions and the offline case.

Next: Camera, Files and Sharing