앱이 Android Auto에서 실행 중인지 Android Automotive OS에서 실행 중인지 확인하려면 CarConnection API를 사용하여 런타임에 연결 정보를 가져옵니다.
예를 들면 다음과 같습니다.
자동차 앱의
Session에서CarConnection를 초기화하고LiveData업데이트를 구독합니다.Kotlin
CarConnection(carContext).type.observe(this, ::onConnectionStateUpdated)자바
new CarConnection(getCarContext()).getType().observe(this, this::onConnectionStateUpdated);관찰자에서 연결 상태의 변경에 반응합니다.
Kotlin
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() }Java
private void onConnectionStateUpdated(int connectionState) { String message; switch(connectionState) { case CarConnection.CONNECTION_TYPE_NOT_CONNECTED: message = "Not connected to a head unit"; break; case CarConnection.CONNECTION_TYPE_NATIVE: message = "Connected to Android Automotive OS"; break; case CarConnection.CONNECTION_TYPE_PROJECTION: message = "Connected to Android Auto"; break; default: message = "Unknown car connection type"; break; } CarToast.makeText(getCarContext(), message, CarToast.LENGTH_SHORT).show(); }