Search code examples
androidchromecastgoogle-cast

Cast icon shows up only first time activity is loaded


I'm using the Chromecast Companion Library and my chromecast icon is displayed the first time my activity is created. But then when I leave the activity and then go back to it, the cast icon won't show. Here's the relevant code for how I'm adding the chromecast icon and updating it's display:

In my layout XML:

<android.support.v7.app.MediaRouteButton
    android:id="@+id/media_route_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:mediaRouteTypes="user"
    android:layout_centerVertical="true"
    android:visibility="gone"
    />

In my activity:

public void onCreate(Bundle savedInstanceState) {
...
mCastManager = RadioPup.getCastManager(this);
    mMediaRouteButton = (MediaRouteButton) findViewById(R.id.media_route_button);
    mCastManager.addMediaRouterButton(mMediaRouteButton);
    setupCastListener();
}

private void setupCastListener() {
    Log.i(LOG_TAG, "SETUP CAST LISTENER");
    mCastConsumer = new VideoCastConsumerImpl() {
        @Override
        public void onCastAvailabilityChanged(boolean castPresent) {
            Log.i(LOG_TAG, "CAST AVAILABILITY CHANGED");
             mMediaRouteButton.setVisibility(castPresent ? View.VISIBLE : 
            View.INVISIBLE);
            }

        @Override
        public void onApplicationConnected(ApplicationMetadata appMetadata,
                String sessionId, boolean wasLaunched) {
            Log.i(LOG_TAG, "CAST APPLICATION CONNECTED");
        }

        @Override
        public void onApplicationDisconnected(int errorCode) {
        }

        @Override
        public void onDisconnected() {
        }

        @Override
        public void onRemoteMediaPlayerMetadataUpdated() {
            try {
            } catch (Exception e) {
                // silent
            }
        }

        @Override
        public void onFailed(int resourceId, int statusCode) {

        }

        @Override
        public void onConnectionSuspended(int cause) {
        }

        @Override
        public void onConnectivityRecovered() {
        }

    };
}

protected void onDestroy() {
...
if (null != mCastManager) {
        Log.i(LOG_TAG, "onDestroy()");
        mCastManager.clearContext(this);
        mCastConsumer = null;
    }
}

protected void onPause() {
...
mCastManager.decrementUiCounter();
    mCastManager.removeVideoCastConsumer(mCastConsumer);
}

protected void onResume() {
...
mCastManager = RadioPup.getCastManager(this);
    mCastManager.incrementUiCounter();
    mCastManager.addVideoCastConsumer(mCastConsumer);
}

Any help is greatly appreciated.


Solution

  • Fixed it by also using this callback method:

            @Override
            public void onCastDeviceDetected(RouteInfo info) {
                Log.i(LOG_TAG, "CAST DEVICE DETECTED");
                mMediaRouteButton.setVisibility(View.VISIBLE);
            }