اتصال API

برای تعیین اینکه آیا برنامه شما روی Android Auto یا Android Automotive OS اجرا می‌شود، از CarConnection API برای بازیابی اطلاعات اتصال در زمان اجرا استفاده کنید. به عنوان مثال:

  1. در Session برنامه ماشین خود، یک CarConnection راه‌اندازی کنید و در به‌روزرسانی‌های LiveData مشترک شوید:

    کاتلین

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

    جاوا

    new CarConnection(getCarContext()).getType().observe(this, this::onConnectionStateUpdated);
    
  2. در ناظر، به تغییرات در وضعیت اتصال واکنش نشان دهید:

    کاتلین

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

    جاوا

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