Android Auto is a popular platform that allows users to seamlessly integrate their Android devices with their car’s infotainment system. This integration extends to navigation, allowing users to launch navigation apps like Google Maps or Waze directly from Android Auto. In this blog post, we’ll explore how to achieve this functionality from within your Android application using .NET MAUI.
The key to launching navigation apps on Android Auto is to construct a URI with the desired latitude and longitude and use an Intent
to open the navigation app. Let’s break down the code snippet you provided to understand how it works:
public class NavigationOnClickListener : Java.Lang.Object, IOnClickListener
{
private readonly CarContext _context;
private readonly double _latitude;
private readonly double _longitude;
public NavigationOnClickListener(CarContext context, double latitude, double longitude)
{
_context = context;
_latitude = latitude;
_longitude = longitude;
}
public void OnClick()
{
string uri = $"geo:{_latitude.ToString(CultureInfo.InvariantCulture)},{_longitude.ToString(CultureInfo.InvariantCulture)}";
Intent intent = new Intent(CarContext.ActionNavigate)
.SetData(AndroidUri.Parse(uri));
_context.StartCarApp(intent);
}
}
AndroidUri is the Android.Net.Uri class alias achieved by:
using AndroidUri = Android.Net.Uri;
Let’s dissect this code step by step:
NavigationOnClickListener
is a custom class that implements theIOnClickListener
interface. This class is responsible for handling the click event that launches the navigation app.- In the constructor, we receive three parameters:
context
,latitude
, andlongitude
.context
is the CarContext instance, andlatitude
andlongitude
are the destination coordinates (double). - Inside the
OnClick
method, we construct a URI in the following format:"geo:latitude,longitude"
. TheCultureInfo.InvariantCulture
is used to ensure that the decimal separator is a period (.) rather than a comma (,) to make the URI universally compatible. This is crucial because different regions may use different formats for numbers. - We create an
Intent
with the actionCarContext.ActionNavigate
. This action specifies that we want to launch a navigation app. - We set the data of the intent by parsing the constructed URI using
AndroidUri.Parse(uri)
. - Finally, we start the navigation app by invoking
_context.StartCarApp(intent)
.