यह पता लगाने के लिए कि आपका ऐप्लिकेशन Android Auto या Android Automotive OS पर चल रहा है या नहीं, CarConnection एपीआई का इस्तेमाल करें. इससे रनटाइम के दौरान कनेक्शन की जानकारी मिलती है.
उदाहरण के लिए:
अपनी कार के ऐप्लिकेशन में मौजूद
Sessionमें जाकर,CarConnectionको शुरू करें औरLiveDataअपडेट के लिए सदस्यता लें:Kotlin
CarConnection(carContext).type.observe(this, ::onConnectionStateUpdated)Java
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(); }