API Kết nối

Để xác định xem ứng dụng của bạn có đang chạy trên Android Auto hay Android Automotive OS hay không, hãy dùng API CarConnection để truy xuất thông tin kết nối trong thời gian chạy. Ví dụ:

  1. Trong Session của ứng dụng dành cho ô tô, hãy khởi chạy CarConnection và đăng ký nhận bản cập nhật LiveData:

    Kotlin

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

    Java

    new CarConnection(getCarContext()).getType().observe(this, this::onConnectionStateUpdated);
    
  2. Trong trình quan sát, hãy phản ứng với các thay đổi về trạng thái kết nối:

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