Integrate with Google Navigation

Guides | Tutorial By 6 years ago

A couple of days ago I explained how to integrate with Google Maps, but what if you want to minimise user clicks and direct them straight to navigation, well you’re in luck. With a few tweaks to the previous code we can direct users straight to Google Navigation using their current location as a start point.

String uri = "google.navigation:ll=%f,%f";
Intent navIntent = new Intent(
    Intent.ACTION_VIEW,
    Uri.parse(String.format(ur, latitude, longitude);
startActivity(navIntent);

There is a small issue with using this code, if Google Navigation isn’t installed or an equivalent app isn’t found to handle the intent your app will force close. A pre-check should be made to check if Google Navigation is installed first, or the resulting exception swallowed and a “friendly” message displayed.

So how do you find out if there is an app available to handle the intent?

public boolean canHandleIntent(Content content, Intent intent){
    PackageManager packageManager = context.getPackageManager();
    List activities = packageManager.queryIntentActivities(
        intent, 
        PackageManager.MATCH_DEFAULT_ONLY);
    return activities.size() > 0;
}

public launchNavigation(Double latitude, Double latitude){
    String uri = "google.navigation:ll=%f,%f";
    Intent navIntent = new Intent(
        Intent.ACTION_VIEW,
        Uri.parse(String.format(ur, latitude, longitude);
    if(canHandleIntent(navIntent))
        startActivity(navIntent);
    else
        Toast.makeText("Please install Google Navigation").show();
}
  • Thank you… you made my day !