com.google.android.gms.cast.Cast Java Examples

The following examples show how to use com.google.android.gms.cast.Cast. 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: VideoCastManager.java    From UTubeTV with The Unlicense 6 votes vote down vote up
/**
 * Sends the <code>message</code> on the data channel for the namespace that was provided during
 * the initialization of this class. If <code>messageId &gt; 0</code>, then it has to be a
 * unique identifier for the message; this id will be returned if an error occurs. If
 * <code>messageId == 0</code>, then an auto-generated unique identifier will be created and
 * returned for the message.
 *
 * @param message
 * @return
 * @throws IllegalStateException                  If the namespace is empty or null
 * @throws NoConnectionException                  If no connectivity to the device exists
 * @throws TransientNetworkDisconnectionException If framework is still trying to recover from a
 *                                                possibly transient loss of network
 */
public void sendDataMessage(String message) throws TransientNetworkDisconnectionException, NoConnectionException {
  if (TextUtils.isEmpty(mDataNamespace)) {
    throw new IllegalStateException("No Data Namespace is configured");
  }
  checkConnectivity();
  Cast.CastApi.sendMessage(mApiClient, mDataNamespace, message)
      .setResultCallback(new ResultCallback<Status>() {

        @Override
        public void onResult(Status result) {
          if (!result.isSuccess()) {
            VideoCastManager.this.onMessageSendFailed(result.getStatusCode());
          }
        }
      });
}
 
Example #2
Source File: CreateRouteRequest.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
@Override
public void onResult(Cast.ApplicationConnectionResult result) {
    if (mState != STATE_LAUNCHING_APPLICATION
            && mState != STATE_API_CONNECTION_SUSPENDED) {
        throwInvalidState();
    }

    Status status = result.getStatus();
    if (!status.isSuccess()) {
        Log.e(TAG, "Launch application failed with status: %s, %d, %s",
                mSource.getApplicationId(), status.getStatusCode(), status.getStatusMessage());
        reportError();
    }

    mState = STATE_LAUNCH_SUCCEEDED;
    reportSuccess(result);
}
 
Example #3
Source File: CastSessionImpl.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
@Override
public void updateSessionStatus() {
    if (isApiClientInvalid()) return;

    try {
        mApplicationStatus = Cast.CastApi.getApplicationStatus(mApiClient);
        mApplicationMetadata = Cast.CastApi.getApplicationMetadata(mApiClient);

        updateNamespaces();

        mMessageHandler.broadcastClientMessage(
                "update_session", mMessageHandler.buildSessionMessage());
    } catch (IllegalStateException e) {
        Log.e(TAG, "Can't get application status", e);
    }
}
 
Example #4
Source File: CastSessionImpl.java    From delion with Apache License 2.0 6 votes vote down vote up
@Override
public void updateSessionStatus() {
    if (isApiClientInvalid()) return;

    try {
        mApplicationStatus = Cast.CastApi.getApplicationStatus(mApiClient);
        mApplicationMetadata = Cast.CastApi.getApplicationMetadata(mApiClient);

        updateNamespaces();

        mMessageHandler.broadcastClientMessage(
                "update_session", mMessageHandler.buildSessionMessage());
    } catch (IllegalStateException e) {
        Log.e(TAG, "Can't get application status", e);
    }
}
 
Example #5
Source File: DataCastManager.java    From android with Apache License 2.0 6 votes vote down vote up
/**
 * Sends the <code>message</code> on the data channel for the <code>namespace</code>. If fails,
 * it will call <code>onMessageSendFailed</code>
 *
 * @param message
 * @param namespace
 * @throws NoConnectionException If no connectivity to the device exists
 * @throws TransientNetworkDisconnectionException If framework is still trying to recover from a
 *             possibly transient loss of network
 * @throws IllegalArgumentException If the the message is null, empty, or too long; or if the
 *             namespace is null or too long.
 * @throws IllegalStateException If there is no active service connection.
 * @throws IOException
 */
public void sendDataMessage(String message, String namespace)
        throws IllegalArgumentException, IllegalStateException, IOException,
        TransientNetworkDisconnectionException, NoConnectionException {
    checkConnectivity();
    if (TextUtils.isEmpty(namespace)) {
        throw new IllegalArgumentException("namespace cannot be empty");
    }
    Cast.CastApi.sendMessage(mApiClient, namespace, message).
            setResultCallback(new ResultCallback<Status>() {

                @Override
                public void onResult(Status result) {
                    if (!result.isSuccess()) {
                        DataCastManager.this.onMessageSendFailed(result);
                    }
                }
            });
}
 
Example #6
Source File: CreateRouteRequest.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
private void reportSuccess(Cast.ApplicationConnectionResult result) {
    if (mState != STATE_LAUNCH_SUCCEEDED) throwInvalidState();

    CastSession session = new CastSessionImpl(
            mApiClient,
            result.getSessionId(),
            result.getApplicationMetadata(),
            result.getApplicationStatus(),
            mSink.getDevice(),
            mOrigin,
            mTabId,
            mIsIncognito,
            mSource,
            mRouteProvider);
    mCastListener.setSession(session);
    mRouteProvider.onSessionCreated(session);

    terminate();
}
 
Example #7
Source File: VideoCastManager.java    From UTubeTV with The Unlicense 6 votes vote down vote up
/**
 * Remove the custom data channel, if any. It returns <code>true</code> if it succeeds otherwise
 * if it encounters an error or if no connection exists or if no custom data channel exists,
 * then it returns <code>false</code>
 */
public boolean removeDataChannel() {
  if (TextUtils.isEmpty(mDataNamespace)) {
    return false;
  }
  try {
    if (null != Cast.CastApi && null != mApiClient) {
      Cast.CastApi.removeMessageReceivedCallbacks(mApiClient, mDataNamespace);
    }
    return true;
  } catch (Exception e) {
    CastUtils.LOGE(TAG, "Failed to remove namespace: " + mDataNamespace, e);
  }
  return false;

}
 
Example #8
Source File: VideoCastManager.java    From android with Apache License 2.0 6 votes vote down vote up
/**
 * Mutes or un-mutes the volume. It internally determines if this should be done for
 * <code>stream</code> or <code>device</code> volume.
 *
 * @param mute
 * @throws CastException
 * @throws NoConnectionException
 * @throws TransientNetworkDisconnectionException
 */
public void setMute(boolean mute) throws CastException, TransientNetworkDisconnectionException,
        NoConnectionException {
    checkConnectivity();
    if (mVolumeType == VolumeType.STREAM) {
        checkRemoteMediaPlayerAvailable();
        mRemoteMediaPlayer.setStreamMute(mApiClient, mute);
    } else {
        try {
            Cast.CastApi.setMute(mApiClient, mute);
        } catch (Exception e) {
            LOGE(TAG, "Failed to set volume", e);
            throw new CastException("Failed to set volume", e);
        }
    }
}
 
Example #9
Source File: VideoCastManager.java    From android with Apache License 2.0 6 votes vote down vote up
private void onApplicationStatusChanged() {
    String appStatus = null;
    if (!isConnected()) {
        return;
    }
    try {
        appStatus = Cast.CastApi.getApplicationStatus(mApiClient);
        LOGD(TAG, "onApplicationStatusChanged() reached: "
                + Cast.CastApi.getApplicationStatus(mApiClient));
        synchronized (mVideoConsumers) {
            for (IVideoCastConsumer consumer : mVideoConsumers) {
                try {
                    consumer.onApplicationStatusChanged(appStatus);
                } catch (Exception e) {
                    LOGE(TAG, "onApplicationStatusChanged(): Failed to inform " + consumer, e);
                }
            }
        }
    } catch (IllegalStateException e1) {
        // no use in logging this
    }
}
 
Example #10
Source File: VideoCastManager.java    From android with Apache License 2.0 6 votes vote down vote up
/**
 * Sends the <code>message</code> on the data channel for the namespace that was provided
 * during the initialization of this class. If <code>messageId &gt; 0</code>, then it has to be
 * a unique identifier for the message; this id will be returned if an error occurs. If
 * <code>messageId == 0</code>, then an auto-generated unique identifier will be created and
 * returned for the message.
 *
 * @param message
 * @return
 * @throws IllegalStateException                  If the namespace is empty or null
 * @throws NoConnectionException                  If no connectivity to the device exists
 * @throws TransientNetworkDisconnectionException If framework is still trying to recover from
 *                                                a possibly transient loss of network
 */
public void sendDataMessage(String message) throws TransientNetworkDisconnectionException,
        NoConnectionException {
    if (TextUtils.isEmpty(mDataNamespace)) {
        throw new IllegalStateException("No Data Namespace is configured");
    }
    checkConnectivity();
    Cast.CastApi.sendMessage(mApiClient, mDataNamespace, message)
            .setResultCallback(new ResultCallback<Status>() {

                @Override
                public void onResult(Status result) {
                    if (!result.isSuccess()) {
                        VideoCastManager.this.onMessageSendFailed(result.getStatusCode());
                    }
                }
            });
}
 
Example #11
Source File: VideoCastManager.java    From android with Apache License 2.0 6 votes vote down vote up
/**
 * Remove the custom data channel, if any. It returns <code>true</code> if it succeeds
 * otherwise if it encounters an error or if no connection exists or if no custom data channel
 * exists, then it returns <code>false</code>
 *
 * @return
 */
public boolean removeDataChannel() {
    if (TextUtils.isEmpty(mDataNamespace)) {
        return false;
    }
    try {
        if (null != Cast.CastApi && null != mApiClient) {
            Cast.CastApi.removeMessageReceivedCallbacks(mApiClient, mDataNamespace);
        }
        mDataChannel = null;
        Utils.saveStringToPreference(mContext, PREFS_KEY_CAST_CUSTOM_DATA_NAMESPACE, null);
        return true;
    } catch (Exception e) {
        LOGE(TAG, "Failed to remove namespace: " + mDataNamespace, e);
    }
    return false;

}
 
Example #12
Source File: BaseCastManager.java    From android with Apache License 2.0 6 votes vote down vote up
/**
 * Stops the application on the receiver device.
 *
 * @throws IllegalStateException
 * @throws IOException
 * @throws NoConnectionException
 * @throws TransientNetworkDisconnectionException
 */
public void stopApplication() throws IllegalStateException, IOException,
        TransientNetworkDisconnectionException, NoConnectionException {
    checkConnectivity();
    Cast.CastApi.stopApplication(mApiClient, mSessionId).setResultCallback(new ResultCallback<Status>() {

        @Override
        public void onResult(Status result) {
            if (!result.isSuccess()) {
                LOGD(TAG, "stopApplication -> onResult: stopping " + "application failed");
                onApplicationStopFailed(result.getStatusCode());
            } else {
                LOGD(TAG, "stopApplication -> onResult Stopped application " + "successfully");
            }
        }
    });
}
 
Example #13
Source File: ChromeCastController.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
@Override
public void onConnected(final Bundle connectionHint) {
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "onConnected:");
    }

    if (mApiClient == null) {
        return;
    }

    if (connectionHint != null && connectionHint.getBoolean(Cast.EXTRA_APP_NO_LONGER_RUNNING)) {
        teardown();
    } else {
        launchApplication();
    }
}
 
Example #14
Source File: ChromeCastController.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * Receiverアプリケーションを起動する.
 * 
 */
private void launchApplication() {
    if (mApiClient != null && mApiClient.isConnected()) {
        Cast.CastApi.launchApplication(mApiClient, mAppId)
            .setResultCallback((result) -> {
                Status status = result.getStatus();
                if (status.isSuccess()) {
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "launchApplication$onResult: Success");
                    }
                    for (int i = 0; i < mCallbacks.size(); i++) {
                        mCallbacks.get(i).onAttach();
                    }

                } else {
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "launchApplication$onResult: Fail");
                    }
                    teardown();
                }
                if (mResult != null) {
                    mResult.onChromeCastConnected();
                }
            });
    }
}
 
Example #15
Source File: CreateRouteRequest.java    From delion with Apache License 2.0 6 votes vote down vote up
private void reportSuccess(Cast.ApplicationConnectionResult result) {
    if (mState != STATE_LAUNCH_SUCCEEDED) throwInvalidState();

    CastSession session = new CastSessionImpl(
            mApiClient,
            result.getSessionId(),
            result.getApplicationMetadata(),
            result.getApplicationStatus(),
            mSink.getDevice(),
            mOrigin,
            mTabId,
            mIsIncognito,
            mSource,
            mRouteProvider);
    mCastListener.setSession(session);
    mRouteProvider.onSessionCreated(session);

    terminate();
}
 
Example #16
Source File: VideoCastManager.java    From UTubeTV with The Unlicense 6 votes vote down vote up
/**
 * ******** Implementing Cast.Listener ********************
 */

private void onApplicationStatusChanged() {
  String appStatus = null;
  if (!isConnected()) {
    return;
  }
  try {
    appStatus = Cast.CastApi.getApplicationStatus(mApiClient);
    CastUtils.LOGD(TAG, "onApplicationStatusChanged() reached: " + Cast.CastApi.getApplicationStatus(mApiClient));

    for (IVideoCastConsumer consumer : mVideoConsumers) {
      try {
        consumer.onApplicationStatusChanged(appStatus);
      } catch (Exception e) {
        CastUtils.LOGE(TAG, "onApplicationStatusChanged(): Failed to inform " + consumer, e);
      }
    }
  } catch (IllegalStateException e1) {
    // no use in logging this
  }
}
 
Example #17
Source File: DataCastManager.java    From UTubeTV with The Unlicense 6 votes vote down vote up
/**
 * *********** Cast.Listener callbacks *********************************
 */

/*
 * Adds namespaces for data channel(s)
 * @throws NoConnectionException If no connectivity to the device exists
 * @throws TransientNetworkDisconnectionException If framework is still trying to recover from a
 * possibly transient loss of network
 * @throws IOException If an I/O error occurs while performing the request.
 * @throws IllegalStateException Thrown when the controller is not connected to a CastDevice.
 * @throws IllegalArgumentException If namespace is null.
 */
private void attachDataChannels() throws IllegalStateException, IOException, TransientNetworkDisconnectionException, NoConnectionException {
  checkConnectivity();
  if (!mNamespaceList.isEmpty() && null != Cast.CastApi) {
    for (String namespace : mNamespaceList) {
      Cast.CastApi.setMessageReceivedCallbacks(mApiClient, namespace, this);
    }
  }
}
 
Example #18
Source File: DataCastManager.java    From UTubeTV with The Unlicense 6 votes vote down vote up
/**
 * Sends the <code>message</code> on the data channel for the <code>namespace</code>. If fails,
 * it will call <code>onMessageSendFailed</code>
 *
 * @param message
 * @param namespace
 * @throws NoConnectionException                  If no connectivity to the device exists
 * @throws TransientNetworkDisconnectionException If framework is still trying to recover from a
 *                                                possibly transient loss of network
 * @throws IllegalArgumentException               If the the message is null, empty, or too long; or if the
 *                                                namespace is null or too long.
 * @throws IllegalStateException                  If there is no active service connection.
 * @throws IOException
 */
public void sendDataMessage(String message, String namespace) throws IllegalArgumentException, IllegalStateException, IOException, TransientNetworkDisconnectionException, NoConnectionException {
  checkConnectivity();
  if (TextUtils.isEmpty(namespace)) {
    throw new IllegalArgumentException("namespace cannot be empty");
  }
  Cast.CastApi.sendMessage(mApiClient, namespace, message).
      setResultCallback(new ResultCallback<Status>() {

        @Override
        public void onResult(Status result) {
          if (!result.isSuccess()) {
            DataCastManager.this.onMessageSendFailed(result);
          }
        }
      });
}
 
Example #19
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
private void teardown() {
    if( mApiClient != null ) {
        if( mApplicationStarted ) {
            try {
                Cast.CastApi.stopApplication( mApiClient );
                if( mRemoteMediaPlayer != null ) {
                    Cast.CastApi.removeMessageReceivedCallbacks( mApiClient, mRemoteMediaPlayer.getNamespace() );
                    mRemoteMediaPlayer = null;
                }
            } catch( IOException e ) {
                //Log.e( TAG, "Exception while removing application " + e );
            }
            mApplicationStarted = false;
        }
        if( mApiClient.isConnected() )
            mApiClient.disconnect();
        mApiClient = null;
    }
    mSelectedDevice = null;
    mVideoIsLoaded = false;
}
 
Example #20
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
private void initCastClientListener() {
    mCastClientListener = new Cast.Listener() {
        @Override
        public void onApplicationStatusChanged() {
        }

        @Override
        public void onVolumeChanged() {
        }

        @Override
        public void onApplicationDisconnected( int statusCode ) {
            teardown();
        }
    };
}
 
Example #21
Source File: ChromeCastController.java    From Popeens-DSub with GNU General Public License v3.0 6 votes vote down vote up
ConnectionCallbacks(boolean isPlaying, int position) {
	this.isPlaying = isPlaying;
	this.position = position;

	resultCallback = new ResultCallback<Cast.ApplicationConnectionResult>() {
		@Override
		public void onResult(Cast.ApplicationConnectionResult result) {
			Status status = result.getStatus();
			if (status.isSuccess()) {
				ApplicationMetadata applicationMetadata = result.getApplicationMetadata();
				sessionId = result.getSessionId();
				String applicationStatus = result.getApplicationStatus();
				boolean wasLaunched = result.getWasLaunched();

				applicationStarted = true;
				setupChannel();
			} else {
				shutdownInternal();
			}
		}
	};
}
 
Example #22
Source File: CastSessionImpl.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@Override
public void updateSessionStatus() {
    if (isApiClientInvalid()) return;

    try {
        mApplicationStatus = Cast.CastApi.getApplicationStatus(mApiClient);
        mApplicationMetadata = Cast.CastApi.getApplicationMetadata(mApiClient);

        updateNamespaces();

        mMessageHandler.broadcastClientMessage(
                "update_session", mMessageHandler.buildSessionMessage());
    } catch (IllegalStateException e) {
        Log.e(TAG, "Can't get application status", e);
    }
}
 
Example #23
Source File: CreateRouteRequest.java    From 365browser with Apache License 2.0 6 votes vote down vote up
private void reportSuccess(Cast.ApplicationConnectionResult result) {
    if (mState != STATE_LAUNCH_SUCCEEDED) throwInvalidState();

    CastSession session = new CastSessionImpl(
            mApiClient,
            result.getSessionId(),
            result.getApplicationMetadata(),
            result.getApplicationStatus(),
            mSink.getDevice(),
            mOrigin,
            mTabId,
            mIsIncognito,
            mSource,
            mRouteProvider);
    mCastListener.setSession(session);
    mRouteProvider.onSessionCreated(session);

    terminate();
}
 
Example #24
Source File: CreateRouteRequest.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@Override
public void onResult(Cast.ApplicationConnectionResult result) {
    if (mState != STATE_LAUNCHING_APPLICATION
            && mState != STATE_API_CONNECTION_SUSPENDED) {
        throwInvalidState();
    }

    Status status = result.getStatus();
    if (!status.isSuccess()) {
        Log.e(TAG, "Launch application failed with status: %s, %d, %s",
                mSource.getApplicationId(), status.getStatusCode(), status.getStatusMessage());
        reportError();
        return;
    }

    mState = STATE_LAUNCH_SUCCEEDED;
    reportSuccess(result);
}
 
Example #25
Source File: ChromeCastMediaPlayer.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
@Override
public void onAttach() {
    mRemoteMediaPlayer = new RemoteMediaPlayer();
    mRemoteMediaPlayer.setOnStatusUpdatedListener(() -> {
        if (mRemoteMediaPlayer.getMediaStatus() == null) {
            return;
        }
        mCallbacks.onChromeCastMediaPlayerStatusUpdate(mRemoteMediaPlayer.getMediaStatus());
    });
    mRemoteMediaPlayer.setOnMetadataUpdatedListener(() -> {
    });

    try {
        Cast.CastApi.setMessageReceivedCallbacks(mController.getGoogleApiClient(),
                mRemoteMediaPlayer.getNamespace(), mRemoteMediaPlayer);
    } catch (Exception e) {
        if (BuildConfig.DEBUG) {
            e.printStackTrace();
        }
    }
}
 
Example #26
Source File: ChromeCastController.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * GoogleApiClientを取得する.
 * <p>
 *     接続に失敗した場合にはnullを返却します。
 * </p>
 * @return GoogleApiClient
 */
public GoogleApiClient getGoogleApiClient()  {
    if (!mApiClient.isConnected()) {
        // 一度切断する
        mApiClient.disconnect();

        Cast.CastOptions.Builder apiOptionsBuilder =
                new Cast.CastOptions.Builder(mSelectedDevice, mCastListener);
        mApiClient = new GoogleApiClient.Builder(mContext)
                .addApi(Cast.API, apiOptionsBuilder.build())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        ConnectionResult result = mApiClient.blockingConnect(30, TimeUnit.SECONDS);
        if (!result.isSuccess()) {
            return null;
        }
    }
    return mApiClient;
}
 
Example #27
Source File: ChromeCastController.java    From Popeens-DSub with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void updateVolume(boolean up) {
	double delta = up ? 0.1 : -0.1;
	gain += delta;
	gain = Math.max(gain, 0.0);
	gain = Math.min(gain, 1.0);

	try {
		Cast.CastApi.setVolume(apiClient, gain);
	} catch(Exception e) {
		Log.e(TAG, "Failed to the volume");
	}
}
 
Example #28
Source File: ChromeCastController.java    From Popeens-DSub with GNU General Public License v3.0 5 votes vote down vote up
void launchApplication() {
	try {
		Cast.CastApi.launchApplication(apiClient, EnvironmentVariables.CAST_APPLICATION_ID, false).setResultCallback(resultCallback);
	} catch (Exception e) {
		Log.e(TAG, "Failed to launch application", e);
	}
}
 
Example #29
Source File: CastSessionImpl.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@Override
public void stopApplication() {
    if (mStoppingApplication) return;

    if (isApiClientInvalid()) return;

    mStoppingApplication = true;
    Cast.CastApi.stopApplication(mApiClient, mSessionId)
            .setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    mMessageHandler.onApplicationStopped();
                    // TODO(avayvod): handle a failure to stop the application.
                    // https://crbug.com/535577

                    Set<String> namespaces = new HashSet<String>(mNamespaces);
                    for (String namespace : namespaces) unregisterNamespace(namespace);
                    mNamespaces.clear();

                    mSessionId = null;
                    mApiClient = null;

                    mRouteProvider.onSessionClosed();
                    mStoppingApplication = false;

                    MediaNotificationManager.clear(R.id.presentation_notification);
                }
            });
}
 
Example #30
Source File: CreateRouteRequest.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
private GoogleApiClient createApiClient(Cast.Listener listener, Context context) {
    Cast.CastOptions.Builder apiOptionsBuilder = Cast.CastOptions
            .builder(mSink.getDevice(), listener)
            // TODO(avayvod): hide this behind the flag or remove
            .setVerboseLoggingEnabled(true);

    return new GoogleApiClient.Builder(context)
            .addApi(Cast.API, apiOptionsBuilder.build())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
}