android.support.v7.media.MediaRouter Java Examples

The following examples show how to use android.support.v7.media.MediaRouter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CastMediaRouterCallback.java    From android with Apache License 2.0 6 votes vote down vote up
@Override
public void onRouteAdded(MediaRouter router, RouteInfo route) {
    super.onRouteAdded(router, route);
    if (!router.getDefaultRoute().equals(route)) {
        if (++mRouteCount == 1) {
            BaseCastManager.getCastManager().onCastAvailabilityChanged(true);
        }
        selectDeviceInterface.onCastDeviceDetected(route);
    }
    if (BaseCastManager.getCastManager().getReconnectionStatus() == ReconnectionStatus.STARTED) {
        String routeId = Utils.getStringFromPreference(mContext,
                BaseCastManager.PREFS_KEY_ROUTE_ID);
        if (route.getId().equals(routeId)) {
            // we found the route, so lets go with that
            LOGD(TAG, "onRouteAdded: Attempting to recover a session with info=" + route);
            BaseCastManager.getCastManager().setReconnectionStatus(
                    ReconnectionStatus.IN_PROGRESS);

            CastDevice device = CastDevice.getFromBundle(route.getExtras());
            LOGD(TAG, "onRouteAdded: Attempting to recover a session with device: "
                    + device.getFriendlyName());
            selectDeviceInterface.onDeviceSelected(device);
        }
    }
}
 
Example #2
Source File: MainActivity.java    From android-MediaRouter with Apache License 2.0 6 votes vote down vote up
private void updateButtons() {
    MediaRouter.RouteInfo route = mMediaRouter.getSelectedRoute();
    // show pause or resume icon depending on current state
    mPauseResumeButton.setImageResource(
            mPaused ? R.drawable.ic_action_play : R.drawable.ic_action_pause);
    // disable pause/resume/stop if no session
    mPauseResumeButton.setEnabled(mSessionManager.hasSession());
    mStopButton.setEnabled(mSessionManager.hasSession());
    // only enable seek bar when duration is known
    PlaylistItem item = getCheckedPlaylistItem();
    mSeekBar.setEnabled(item != null && item.getDuration() > 0);
    if (mRemoteControlClient != null) {
        mRemoteControlClient.setPlaybackState(mPaused ? RemoteControlClient.PLAYSTATE_PAUSED :
                RemoteControlClient.PLAYSTATE_PLAYING);
    }
}
 
Example #3
Source File: AbstractMediaRouteController.java    From delion with Apache License 2.0 6 votes vote down vote up
@Override
public void onRouteChanged(MediaRouter router, RouteInfo route) {
    // We only care about changes to the current route.
    if (!route.equals(getCurrentRoute())) return;
    // When there is no wifi connection, this condition becomes true.
    if (route.isConnecting()) {
        // We don't want to post the same Runnable twice.
        if (!mConnectionFailureNotifierQueued) {
            mConnectionFailureNotifierQueued = true;
            getHandler().postDelayed(mConnectionFailureNotifier,
                    CONNECTION_FAILURE_NOTIFICATION_DELAY_MS);
        }
    } else {
        // Only cancel the disconnect if we already posted the message. We can get into this
        // situation if we swap the current route provider (for example, switching to a YT
        // video while casting a non-YT video).
        if (mConnectionFailureNotifierQueued) {
            // We have reconnected, cancel the delayed disconnect.
            getHandler().removeCallbacks(mConnectionFailureNotifier);
            mConnectionFailureNotifierQueued = false;
        }
    }
}
 
Example #4
Source File: BaseCastManager.java    From UTubeTV with The Unlicense 6 votes vote down vote up
/**
 * ********************************************************************
 */

protected BaseCastManager(Context context, String applicationId) {
  CastUtils.LOGD(TAG, "BaseCastManager is instantiated");
  mContext = context;
  mHandler = new Handler(Looper.getMainLooper());
  mApplicationId = applicationId;
  CastUtils.saveStringToPreference(mContext, PREFS_KEY_APPLICATION_ID, applicationId);

  CastUtils.LOGD(TAG, "Application ID is: " + mApplicationId);
  mMediaRouter = MediaRouter.getInstance(context);
  mMediaRouteSelector = new MediaRouteSelector.Builder().addControlCategory(CastMediaControlIntent
      .categoryForCast(mApplicationId)).build();

  mMediaRouterCallback = new CastMediaRouterCallback(this, context);
  mMediaRouter.addCallback(mMediaRouteSelector, mMediaRouterCallback, MediaRouter.CALLBACK_FLAG_PERFORM_ACTIVE_SCAN);
}
 
Example #5
Source File: MediaNotificationManager.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
private void updateMediaSession() {
    if (!mMediaNotificationInfo.supportsPlayPause()) return;

    if (mMediaSession == null) mMediaSession = createMediaSession();

    try {
        // Tell the MediaRouter about the session, so that Chrome can control the volume
        // on the remote cast device (if any).
        // Pre-MR1 versions of JB do not have the complete MediaRouter APIs,
        // so getting the MediaRouter instance will throw an exception.
        MediaRouter.getInstance(mContext).setMediaSessionCompat(mMediaSession);
    } catch (NoSuchMethodError e) {
        // Do nothing. Chrome can't be casting without a MediaRouter, so there is nothing
        // to do here.
    }

    mMediaSession.setMetadata(createMetadata());

    PlaybackStateCompat.Builder playbackStateBuilder =
            new PlaybackStateCompat.Builder().setActions(computeMediaSessionActions());
    if (mMediaNotificationInfo.isPaused) {
        playbackStateBuilder.setState(PlaybackStateCompat.STATE_PAUSED,
                PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1.0f);
    } else {
        // If notification only supports stop, still pretend
        playbackStateBuilder.setState(PlaybackStateCompat.STATE_PLAYING,
                PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1.0f);
    }
    mMediaSession.setPlaybackState(playbackStateBuilder.build());
}
 
Example #6
Source File: AbstractMediaRouteController.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@Override
public void onRouteUnselected(MediaRouter router, RouteInfo route) {
    onRouteUnselectedEvent(router, route);
    if (getCurrentRoute() != null && !getCurrentRoute().isDefault()
            && route.getId().equals(getCurrentRoute().getId())) {
        RecordCastAction.castEndedTimeRemaining(getDuration(),
                getDuration() - getPosition());
        release();
    }
}
 
Example #7
Source File: MediaSink.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * @param sinkId The id of the sink to find among known media routes.
 * @param router The instance of {@link MediaRouter} to enumerate the routes with.
 * @return A {@link MediaSink} corresponding to the {@link RouteInfo} with the specified id if
 * found, null otherwise.
 */
@Nullable
public static MediaSink fromSinkId(String sinkId, MediaRouter router) {
    for (MediaRouter.RouteInfo route : router.getRoutes()) {
        MediaSink sink = MediaSink.fromRoute(route);
        if (sink.getId().equals(sinkId)) return sink;
    }
    return null;
}
 
Example #8
Source File: MediaSink.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * @param route The route information provided by Android.
 * @return A new MediaSink instance corresponding to the specified {@link RouteInfo}.
 */
public static MediaSink fromRoute(MediaRouter.RouteInfo route) {
    return new MediaSink(
        route.getId(),
        route.getName(),
        CastDevice.getFromBundle(route.getExtras()));
}
 
Example #9
Source File: MediaRouteChooserDialogFactory.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@Override
public void onDismiss(DialogInterface dialog) {
    super.onDismiss(dialog);

    if (mCancelled) {
        if (mPlayer != null) mPlayer.onRouteDialogCancelled();
        return;
    }

    if (mController != null) {
        MediaRouter router = MediaRouter.getInstance(mContext);
        mController.onRouteSelected(mPlayer, router, router.getSelectedRoute());
    }
}
 
Example #10
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
@Override
public void onRouteUnselected( MediaRouter router, RouteInfo info ) {
    teardown();
    mSelectedDevice = null;
    mButton.setText( getString( R.string.play_video ) );
    mVideoIsLoaded = false;
}
 
Example #11
Source File: MediaRouteChooserDialogFactory.java    From delion with Apache License 2.0 5 votes vote down vote up
@Override
public void onDismiss(DialogInterface dialog) {
    super.onDismiss(dialog);

    if (mCancelled) {
        if (mPlayer != null) mPlayer.onRouteDialogCancelled();
        return;
    }

    if (mController != null) {
        MediaRouter router = MediaRouter.getInstance(mContext);
        mController.onRouteSelected(mPlayer, router, router.getSelectedRoute());
    }
}
 
Example #12
Source File: DiscoveryCallback.java    From delion with Apache License 2.0 5 votes vote down vote up
@Override
public void onRouteChanged(MediaRouter router, MediaRouter.RouteInfo route) {
    // Sometimes onRouteAdded is not called for the route as it doesn't yet match the selector.
    // onRouteChanged() will be called later when the matching category is added.
    if (route == null) return;

    if (route.matchesSelector(mRouteSelector)) {
        onRouteAdded(router, route);
    } else {
        onRouteRemoved(router, route);
    }
}
 
Example #13
Source File: DiscoveryCallback.java    From delion with Apache License 2.0 5 votes vote down vote up
@Override
public void onRouteRemoved(MediaRouter router, MediaRouter.RouteInfo route) {
    MediaSink sink = MediaSink.fromRoute(route);
    if (!mSinks.contains(sink)) return;
    mSinks.remove(sink);
    updateChromeMediaRouter();
}
 
Example #14
Source File: DiscoveryCallback.java    From delion with Apache License 2.0 5 votes vote down vote up
@Override
public void onRouteAdded(MediaRouter router, MediaRouter.RouteInfo route) {
    if (route == null || !route.matchesSelector(mRouteSelector)) return;

    MediaSink sink = MediaSink.fromRoute(route);
    if (mSinks.contains(sink)) return;
    mSinks.add(sink);
    updateChromeMediaRouter();
}
 
Example #15
Source File: CastMediaRouteProvider.java    From delion with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
CastMediaRouteProvider(
        Context applicationContext, MediaRouter androidMediaRouter, MediaRouteManager manager) {
    mApplicationContext = applicationContext;
    mAndroidMediaRouter = androidMediaRouter;
    mManager = manager;
    mMessageHandler = new CastMessageHandler(this);
}
 
Example #16
Source File: MainActivity.java    From android-MediaRouter with Apache License 2.0 5 votes vote down vote up
@Override
public void onRouteUnselected(MediaRouter router, RouteInfo route) {
    Log.d(TAG, "onRouteUnselected: route=" + route);
    unregisterRemoteControlClient();

    PlaylistItem item = getCheckedPlaylistItem();
    if (item != null) {
        long pos = item.getPosition() +
                (mPaused ? 0 : (SystemClock.elapsedRealtime() - item.getTimestamp()));
        mSessionManager.suspend(pos);
    }
    mPlayer.updatePresentation();
    mPlayer.release();
}
 
Example #17
Source File: DefaultMediaRouteController.java    From delion with Apache License 2.0 5 votes vote down vote up
@Override
public void setRemoteVolume(int delta) {
    boolean canChangeRemoteVolume = (getCurrentRoute().getVolumeHandling()
            == MediaRouter.RouteInfo.PLAYBACK_VOLUME_VARIABLE);
    if (currentRouteSupportsRemotePlayback() && canChangeRemoteVolume) {
        getCurrentRoute().requestUpdateVolume(delta);
    }
}
 
Example #18
Source File: DefaultMediaRouteController.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@Override
protected void onRouteUnselectedEvent(MediaRouter router, RouteInfo route) {
    Log.d(TAG, "Unselected route %s", route);
    // Preserve our best guess as to the final position; this is needed to reset the
    // local position while switching back to local playback.
    mPositionExtrapolator.onPaused();
    if (getCurrentRoute() != null && route.getId().equals(getCurrentRoute().getId())) {
        clearStreamState();
    }
}
 
Example #19
Source File: AbstractMediaRouteController.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
protected AbstractMediaRouteController() {
    mContext = ContextUtils.getApplicationContext();
    assert (getContext() != null);

    mHandler = new Handler();

    mMediaRouteSelector = buildMediaRouteSelector();

    MediaRouter mediaRouter;

    try {
        // Pre-MR1 versions of JB do not have the complete MediaRouter APIs,
        // so getting the MediaRouter instance will throw an exception.
        mediaRouter = MediaRouter.getInstance(getContext());
    } catch (NoSuchMethodError e) {
        Log.e(TAG, "Can't get an instance of MediaRouter, casting is not supported."
                + " Are you still on JB (JVP15S)?");
        mediaRouter = null;
    }
    mMediaRouter = mediaRouter;

    mAvailableRouteListeners = new HashSet<MediaStateListener>();
    // TODO(aberent): I am unclear why this is accessed from multiple threads, but
    // if I make it a HashSet then it gets ConcurrentModificationExceptions on some
    // types of disconnect. Investigate and fix.
    mUiListeners = new CopyOnWriteArraySet<UiListener>();

    mDeviceDiscoveryCallback = new DeviceDiscoveryCallback();
    mDeviceSelectionCallback = new DeviceSelectionCallback();
}
 
Example #20
Source File: DiscoveryCallback.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@Override
public void onRouteChanged(MediaRouter router, MediaRouter.RouteInfo route) {
    // Sometimes onRouteAdded is not called for the route as it doesn't yet match the selector.
    // onRouteChanged() will be called later when the matching category is added.
    if (route == null) return;

    if (route.matchesSelector(mRouteSelector)) {
        onRouteAdded(router, route);
    } else {
        onRouteRemoved(router, route);
    }
}
 
Example #21
Source File: AbstractMediaRouteController.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@Override
public final boolean isRemotePlaybackAvailable() {
    if (mediaRouterInitializationFailed()) return false;

    return getMediaRouter().getSelectedRoute().getPlaybackType()
            == MediaRouter.RouteInfo.PLAYBACK_TYPE_REMOTE || getMediaRouter().isRouteAvailable(
            mMediaRouteSelector, MediaRouter.AVAILABILITY_FLAG_IGNORE_DEFAULT_ROUTE);
}
 
Example #22
Source File: MediaSink.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * @param route The route information provided by Android.
 * @return A new MediaSink instance corresponding to the specified {@link RouteInfo}.
 */
public static MediaSink fromRoute(MediaRouter.RouteInfo route) {
    return new MediaSink(
        route.getId(),
        route.getName(),
        CastDevice.getFromBundle(route.getExtras()));
}
 
Example #23
Source File: CastMediaRouteProvider.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@Override
public void startObservingMediaSinks(String sourceId) {
    if (mAndroidMediaRouter == null) return;

    MediaSource source = MediaSource.from(sourceId);
    if (source == null) return;

    MediaRouteSelector routeSelector = source.buildRouteSelector();
    if (routeSelector == null) {
        // If the application invalid, report no devices available.
        onSinksReceived(sourceId, new ArrayList<MediaSink>());
        return;
    }

    String applicationId = source.getApplicationId();
    DiscoveryCallback callback = mDiscoveryCallbacks.get(applicationId);
    if (callback != null) {
        callback.addSourceUrn(sourceId);
        return;
    }

    List<MediaSink> knownSinks = new ArrayList<MediaSink>();
    for (RouteInfo route : mAndroidMediaRouter.getRoutes()) {
        if (route.matchesSelector(routeSelector)) {
            knownSinks.add(MediaSink.fromRoute(route));
        }
    }

    callback = new DiscoveryCallback(sourceId, knownSinks, this, routeSelector);
    mAndroidMediaRouter.addCallback(
            routeSelector,
            callback,
            MediaRouter.CALLBACK_FLAG_REQUEST_DISCOVERY);
    mDiscoveryCallbacks.put(applicationId, callback);
}
 
Example #24
Source File: CastMediaRouteProvider.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
CastMediaRouteProvider(
        Context applicationContext, MediaRouter androidMediaRouter, MediaRouteManager manager) {
    mApplicationContext = applicationContext;
    mAndroidMediaRouter = androidMediaRouter;
    mManager = manager;
    mMessageHandler = new CastMessageHandler(this);
}
 
Example #25
Source File: DiscoveryCallback.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@Override
public void onRouteAdded(MediaRouter router, MediaRouter.RouteInfo route) {
    if (route == null || !route.matchesSelector(mRouteSelector)) return;

    MediaSink sink = MediaSink.fromRoute(route);
    if (mSinks.contains(sink)) return;
    mSinks.add(sink);
    updateChromeMediaRouter();
}
 
Example #26
Source File: DiscoveryCallback.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@Override
public void onRouteRemoved(MediaRouter router, MediaRouter.RouteInfo route) {
    MediaSink sink = MediaSink.fromRoute(route);
    if (!mSinks.contains(sink)) return;
    mSinks.remove(sink);
    updateChromeMediaRouter();
}
 
Example #27
Source File: DefaultMediaRouteController.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@Override
public void setRemoteVolume(int delta) {
    boolean canChangeRemoteVolume = (getCurrentRoute().getVolumeHandling()
            == MediaRouter.RouteInfo.PLAYBACK_VOLUME_VARIABLE);
    if (currentRouteSupportsRemotePlayback() && canChangeRemoteVolume) {
        getCurrentRoute().requestUpdateVolume(delta);
    }
}
 
Example #28
Source File: BaseCastManager.java    From android with Apache License 2.0 5 votes vote down vote up
/**
 * This is called when UI visibility of the client has changed
 *
 * @param visible The updated visibility status
 */
protected void onUiVisibilityChanged(boolean visible) {
    if (visible) {
        if (null != mMediaRouter && null != mMediaRouterCallback) {
            LOGD(TAG, "onUiVisibilityChanged() addCallback called");
            mMediaRouter.addCallback(mMediaRouteSelector, mMediaRouterCallback,
                    MediaRouter.CALLBACK_FLAG_PERFORM_ACTIVE_SCAN);
        }
    } else {
        if (null != mMediaRouter) {
            LOGD(TAG, "onUiVisibilityChanged() removeCallback called");
            mMediaRouter.removeCallback(mMediaRouterCallback);
        }
    }
}
 
Example #29
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
@Override
public void onRouteSelected(MediaRouter router, RouteInfo info) {
    initCastClientListener();
    initRemoteMediaPlayer();

    mSelectedDevice = CastDevice.getFromBundle( info.getExtras() );

    launchReceiver();
}
 
Example #30
Source File: CastMediaRouterCallback.java    From UTubeTV with The Unlicense 5 votes vote down vote up
@Override
public void onRouteSelected(MediaRouter router, RouteInfo info) {
  CastUtils.LOGD(TAG, "onRouteSelected: info=" + info);
  if (BaseCastManager.getCastManager()
      .getReconnectionStatus() == BaseCastManager.ReconnectionStatus.FINALIZE) {
    BaseCastManager.getCastManager().setReconnectionStatus(ReconnectionStatus.INACTIVE);
    BaseCastManager.getCastManager().cancelReconnectionTask();
    return;
  }
  CastUtils.saveStringToPreference(mContext, BaseCastManager.PREFS_KEY_ROUTE_ID, info.getId());
  CastDevice device = CastDevice.getFromBundle(info.getExtras());
  selectDeviceInterface.onDeviceSelected(device);
  CastUtils.LOGD(TAG, "onResult: mSelectedDevice=" + device.getFriendlyName());
}