連線 API

如要判斷應用程式是否在 Android Auto 或 Android Automotive OS 上執行,請使用 CarConnection API 在執行階段擷取連線資訊。例如:

  1. 在車用應用程式的 Session 中,初始化 CarConnection 並訂閱 LiveData 更新:

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

  1. 在觀察器中,回應連線狀態的變更:

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