0

I want to use CastStateListener in a fragment to check if casting devices are available or not. Code used in Fragment is

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mCastContext = CastContext.getSharedInstance(mContext)
        mCastStateListener = CastStateListener { newState ->
            if (newState != CastState.NO_DEVICES_AVAILABLE) {
                castDevicesAvailable = true
            }
        }
    }

    override fun onResume() {
        super.onResume()
        mCastContext?.addCastStateListener(mCastStateListener)
    }


    override fun onPause() {
        super.onPause()
        mCastContext?.removeCastStateListener(mCastStateListener)
    }

This code does not give me a call back inside CastListner when used in Fragment but it works fine when I use it in an Activity or Fragment.

I am using custom view

<androidx.mediarouter.app.MediaRouteButton
                    android:id="@+id/media_route_button"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:actionButtonStyle="@android:style/Widget.Holo.Light.MediaRouteButton"/>

I want to hide/show the view based on cast devices available

1 Answer 1

0

I don't think it is a good idea to use CastStateListener in a fragment. Because an activity can host multiple fragments. When a activity is paused, all fragments in it are paused, so are resumed. In the code, if you add CastStateListener in fragment onResume and remove CastStateListener in fragment onPause. If the activity hosts multiple fragments, it is very easy to mess up the add/remove CastStateListener. So I think it is better to add/remove the CastStateListener to the activity life cycle

Not the answer you're looking for? Browse other questions tagged or ask your own question.