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