public class

MediaRouteDiscoveryFragment

extends Fragment

 java.lang.Object

androidx.fragment.app.Fragment

↳androidx.mediarouter.app.MediaRouteDiscoveryFragment

Gradle dependencies

compile group: 'androidx.mediarouter', name: 'mediarouter', version: '1.7.0'

  • groupId: androidx.mediarouter
  • artifactId: mediarouter
  • version: 1.7.0

Artifact androidx.mediarouter:mediarouter:1.7.0 it located at Google repository (https://maven.google.com/)

Androidx artifact mapping:

androidx.mediarouter:mediarouter com.android.support:mediarouter-v7

Androidx class mapping:

androidx.mediarouter.app.MediaRouteDiscoveryFragment android.support.v7.app.MediaRouteDiscoveryFragment

Overview

Media route discovery fragment.

This fragment takes care of registering a callback with proper flags for media route discovery:

The application must supply a route selector to specify the kinds of routes to discover. The application may also override MediaRouteDiscoveryFragment.onCreateCallback() to provide the MediaRouter callback to register.

Note that the discovery callback makes the application be connected with all the media route provider services while it is registered.

Summary

Fields
from FragmentmPreviousWho
Constructors
publicMediaRouteDiscoveryFragment()

Methods
public MediaRoutergetMediaRouter()

Gets the media router instance.

public MediaRouteSelectorgetRouteSelector()

Gets the media route selector for filtering the routes to be discovered.

public voidonCreate(Bundle savedInstanceState)

Called to do initial creation of a fragment.

public MediaRouter.CallbackonCreateCallback()

Called to create the callback that will be registered.

public voidonDestroy()

Called when the fragment is no longer in use.

public intonPrepareCallbackFlags()

Called to prepare the callback flags that will be used when the callback is registered.

public voidonStart()

Called when the Fragment is visible to the user.

public voidonStop()

Called when the Fragment is no longer started.

public voidsetRouteSelector(MediaRouteSelector selector)

Sets the media route selector for filtering the routes to be discovered.

from Fragmentdump, equals, getActivity, getAllowEnterTransitionOverlap, getAllowReturnTransitionOverlap, getArguments, getChildFragmentManager, getContext, getDefaultViewModelCreationExtras, getDefaultViewModelProviderFactory, getEnterTransition, getExitTransition, getFragmentManager, getHost, getId, getLayoutInflater, getLayoutInflater, getLifecycle, getLoaderManager, getParentFragment, getParentFragmentManager, getReenterTransition, getResources, getRetainInstance, getReturnTransition, getSavedStateRegistry, getSharedElementEnterTransition, getSharedElementReturnTransition, getString, getString, getTag, getTargetFragment, getTargetRequestCode, getText, getUserVisibleHint, getView, getViewLifecycleOwner, getViewLifecycleOwnerLiveData, getViewModelStore, hashCode, hasOptionsMenu, instantiate, instantiate, isAdded, isDetached, isHidden, isInLayout, isMenuVisible, isRemoving, isResumed, isStateSaved, isVisible, onActivityCreated, onActivityResult, onAttach, onAttach, onAttachFragment, onConfigurationChanged, onContextItemSelected, onCreateAnimation, onCreateAnimator, onCreateContextMenu, onCreateOptionsMenu, onCreateView, onDestroyOptionsMenu, onDestroyView, onDetach, onGetLayoutInflater, onHiddenChanged, onInflate, onInflate, onLowMemory, onMultiWindowModeChanged, onOptionsItemSelected, onOptionsMenuClosed, onPause, onPictureInPictureModeChanged, onPrepareOptionsMenu, onPrimaryNavigationFragmentChanged, onRequestPermissionsResult, onResume, onSaveInstanceState, onViewCreated, onViewStateRestored, postponeEnterTransition, postponeEnterTransition, registerForActivityResult, registerForActivityResult, registerForContextMenu, requestPermissions, requireActivity, requireArguments, requireContext, requireFragmentManager, requireHost, requireParentFragment, requireView, setAllowEnterTransitionOverlap, setAllowReturnTransitionOverlap, setArguments, setEnterSharedElementCallback, setEnterTransition, setExitSharedElementCallback, setExitTransition, setHasOptionsMenu, setInitialSavedState, setMenuVisibility, setReenterTransition, setRetainInstance, setReturnTransition, setSharedElementEnterTransition, setSharedElementReturnTransition, setTargetFragment, setUserVisibleHint, shouldShowRequestPermissionRationale, startActivity, startActivity, startActivityForResult, startActivityForResult, startIntentSenderForResult, startPostponedEnterTransition, toString, unregisterForContextMenu
from java.lang.Objectclone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructors

public MediaRouteDiscoveryFragment()

Methods

public MediaRouter getMediaRouter()

Gets the media router instance.

public MediaRouteSelector getRouteSelector()

Gets the media route selector for filtering the routes to be discovered.

Returns:

The selector, never null.

public void setRouteSelector(MediaRouteSelector selector)

Sets the media route selector for filtering the routes to be discovered. This method must be called before the fragment is added.

Parameters:

selector: The selector to set.

public MediaRouter.Callback onCreateCallback()

Called to create the callback that will be registered.

The default callback does nothing. The application may override this method to supply its own callback.

Returns:

The new callback, or null if no callback should be registered.

public int onPrepareCallbackFlags()

Called to prepare the callback flags that will be used when the callback is registered.

The default implementation returns MediaRouter.CALLBACK_FLAG_REQUEST_DISCOVERY.

Returns:

The desired callback flags.

public void onCreate(Bundle savedInstanceState)

Called to do initial creation of a fragment. This is called after Fragment.onAttach(Activity) and before Fragment.onCreateView(LayoutInflater, ViewGroup, Bundle).

Note that this can be called while the fragment's activity is still in the process of being created. As such, you can not rely on things like the activity's content view hierarchy being initialized at this point. If you want to do work once the activity itself is created, add a LifecycleObserver on the activity's Lifecycle, removing it when it receives the callback.

Any restored child fragments will be created before the base Fragment.onCreate method returns.

Parameters:

savedInstanceState: If the fragment is being re-created from a previous saved state, this is the state.

public void onStart()

Called when the Fragment is visible to the user. This is generally tied to of the containing Activity's lifecycle.

public void onStop()

Called when the Fragment is no longer started. This is generally tied to of the containing Activity's lifecycle.

public void onDestroy()

Called when the fragment is no longer in use. This is called after Fragment.onStop() and before Fragment.onDetach().

Source

/*
 * Copyright 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package androidx.mediarouter.app;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.mediarouter.media.MediaRouteSelector;
import androidx.mediarouter.media.MediaRouter;

/**
 * Media route discovery fragment.
 * <p>
 * This fragment takes care of registering a callback with proper flags for media route discovery:
 * <ul>
 *      <li>In {@link Fragment#onCreate} phase, the callback is registered with zero flags. </li>
 *      <li>In {@link Fragment#onStart} phase, the callback's flags are set to the value
 *          which is provided by {@link #onPrepareCallbackFlags()}.</li>
 *      <li>In {@link Fragment#onStop()} phase, the callback's flags are set to zero. </li>
 * </ul>
 * </p><p>
 * The application must supply a route selector to specify the kinds of routes
 * to discover.  The application may also override {@link #onCreateCallback} to
 * provide the {@link MediaRouter} callback to register.
 * </p><p>
 * Note that the discovery callback makes the application be connected with all the
 * {@link androidx.mediarouter.media.MediaRouteProviderService media route provider services}
 * while it is registered.
 * </p>
 */
public class MediaRouteDiscoveryFragment extends Fragment {
    private static final String ARGUMENT_SELECTOR = "selector";

    private MediaRouter mRouter;
    private MediaRouteSelector mSelector;
    private MediaRouter.Callback mCallback;

    public MediaRouteDiscoveryFragment() {
    }

    /**
     * Gets the media router instance.
     */
    @NonNull
    public MediaRouter getMediaRouter() {
        ensureRouter();
        return mRouter;
    }

    private void ensureRouter() {
        if (mRouter == null) {
            mRouter = MediaRouter.getInstance(getContext());
        }
    }

    /**
     * Gets the media route selector for filtering the routes to be discovered.
     *
     * @return The selector, never null.
     */
    @NonNull
    public MediaRouteSelector getRouteSelector() {
        ensureRouteSelector();
        return mSelector;
    }

    /**
     * Sets the media route selector for filtering the routes to be discovered.
     * This method must be called before the fragment is added.
     *
     * @param selector The selector to set.
     */
    public void setRouteSelector(@NonNull MediaRouteSelector selector) {
        if (selector == null) {
            throw new IllegalArgumentException("selector must not be null");
        }

        ensureRouteSelector();
        if (!mSelector.equals(selector)) {
            mSelector = selector;

            Bundle args = getArguments();
            if (args == null) {
                args = new Bundle();
            }
            args.putBundle(ARGUMENT_SELECTOR, selector.asBundle());
            setArguments(args);

            if (mCallback != null) {
                mRouter.removeCallback(mCallback);
                mRouter.addCallback(mSelector, mCallback, onPrepareCallbackFlags());
            }
        }
    }

    private void ensureRouteSelector() {
        if (mSelector == null) {
            Bundle args = getArguments();
            if (args != null) {
                mSelector = MediaRouteSelector.fromBundle(args.getBundle(ARGUMENT_SELECTOR));
            }
            if (mSelector == null) {
                mSelector = MediaRouteSelector.EMPTY;
            }
        }
    }

    /**
     * Called to create the {@link androidx.mediarouter.media.MediaRouter.Callback callback}
     * that will be registered.
     * <p>
     * The default callback does nothing.  The application may override this method to
     * supply its own callback.
     * </p>
     *
     * @return The new callback, or null if no callback should be registered.
     */
    @Nullable
    public MediaRouter.Callback onCreateCallback() {
        return new MediaRouter.Callback() { };
    }

    /**
     * Called to prepare the callback flags that will be used when the
     * {@link androidx.mediarouter.media.MediaRouter.Callback callback} is registered.
     * <p>
     * The default implementation returns {@link MediaRouter#CALLBACK_FLAG_REQUEST_DISCOVERY}.
     * </p>
     *
     * @return The desired callback flags.
     */
    public int onPrepareCallbackFlags() {
        return MediaRouter.CALLBACK_FLAG_REQUEST_DISCOVERY;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ensureRouteSelector();
        ensureRouter();
        mCallback = onCreateCallback();
        if (mCallback != null) {
            mRouter.addCallback(mSelector, mCallback, 0);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (mCallback != null) {
            mRouter.addCallback(mSelector, mCallback, onPrepareCallbackFlags());
        }
    }

    @Override
    public void onStop() {
        if (mCallback != null) {
            mRouter.addCallback(mSelector, mCallback, 0);
        }
        super.onStop();
    }

    @Override
    public void onDestroy() {
        if (mCallback != null) {
            mRouter.removeCallback(mCallback);
        }
        super.onDestroy();
    }
}