Checking for Google Play Services with Kotlin

In many countries we can assume Android users use devices that have Google Play Services pre-installed, but not every Android device in the world actually does. It's possible that code written with the assumption that Play Services is available may crash--something we certainly don't want.

What we do want is to have the app either fail silently (e.g. location is not discovered because Play Location is not available), or report to the user that some feature doesn't work  (or that the entire app is unusable, if that's the case) because Google Play Services isn't installed.

Code a Play Services Detection Routine

Fortunately it's possible to interrogate a device for Play Services support proactively, and then use application logic to decide what to do (fail silently, report error, etc.).

Code for the detection is as follows.

fun checkForGooglePlayServices(activity: Activity?, displayError: Boolean = false): Boolean {
  activity?.let { unwrappedActivity ->
	  val googleApiAvailability = GoogleApiAvailability.getInstance()
    val status = googleApiAvailability.isGooglePlayServicesAvailable(unwrappedActivity)
                 
    if (status != ConnectionResult.SUCCESS) {
    	if (googleApiAvailability.isUserResolvableError(status) && displayError) {
      	googleApiAvailability.getErrorDialog(unwrappedActivity, status, 2404)!!.show()
      }
      return false
    }
    return true
	} ?: run {
    Log.d(TAG, "##### NULLL activity passed to checkForGooglePlayServices (programming error)")
    return false
  }
}

This routine accepts the optional parameter displayError, which if set to true will show a general error message before returning false. This could be useful if an app is so dependent on Google Play Services that it's unusable.