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()
}