ממשק API לחיבור

כדי לקבוע אם האפליקציה פועלת ב-Android Auto או ב-Android Automotive OS, צריך להשתמש ב-CarConnection API כדי לאחזר מידע על החיבור בזמן ריצה. לדוגמה:

  1. באפליקציית הרכב Session, מאתחלים CarConnection ונרשמים לעדכונים של LiveData:

CarConnection(carContext).type.observe(this, ::onConnectionStateUpdated)

  1. ב-observer, מגיבים לשינויים במצב החיבור:

fun onConnectionStateUpdated(connectionState: Int) {
    val message = when (connectionState) {
        CarConnection.CONNECTION_TYPE_NOT_CONNECTED -> "Not connected to a head unit"
        CarConnection.CONNECTION_TYPE_NATIVE -> "Connected to Android Automotive OS"
        CarConnection.CONNECTION_TYPE_PROJECTION -> "Connected to Android Auto"
        else -> "Unknown car connection type"
    }
    CarToast.makeText(carContext, message, CarToast.LENGTH_SHORT).show()
}