如要判斷應用程式是否在 Android Auto 或 Android Automotive OS 上執行,請使用 CarConnection API 在執行階段擷取連線資訊。例如:
- 在車用應用程式的
Session中,初始化CarConnection並訂閱LiveData更新:
CarConnection(carContext).type.observe(this, ::onConnectionStateUpdated)
- 在觀察器中,回應連線狀態的變更:
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() }