com.google.android.gms.cast.framework.CastContext Java Examples

The following examples show how to use com.google.android.gms.cast.framework.CastContext. 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: MainActivity.java    From vinyl-cast with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    CastContext.getSharedInstance(this).getSessionManager();

    statusText = findViewById(R.id.statusText);

    // button to begin audio record
    startRecordingButton = findViewById(R.id.startRecordingButton);
    startRecordingButton.setOnClickListener(v -> startRecordingButtonClicked());

    playStopButton = findViewById(R.id.play_stop_view);
    playStopButton.setOnClickListener(v -> {
        playStopButton.toggle();
        startRecordingButtonClicked();
    });

    barGraphView = findViewById(R.id.audio_visualizer);
}
 
Example #2
Source File: GoogleCastModule.java    From react-native-google-cast with MIT License 6 votes vote down vote up
@ReactMethod
public void endSession(final boolean stopCasting, final Promise promise) {
    getReactApplicationContext().runOnUiQueueThread(new Runnable() {
        @Override
        public void run() {
            if (CAST_AVAILABLE) {
                SessionManager sessionManager =
                    CastContext.getSharedInstance(getReactApplicationContext())
                            .getSessionManager();
                sessionManager.endCurrentSession(stopCasting);
                promise.resolve(true);
            } else {
                promise.reject(E_CAST_NOT_AVAILABLE, GOOGLE_CAST_NOT_AVAILABLE_MESSAGE);
            }
        }
    });
}
 
Example #3
Source File: GoogleCastButtonManager.java    From react-native-google-cast with MIT License 6 votes vote down vote up
@Override
public MediaRouteButton createViewInstance(ThemedReactContext context) {
  CastContext castContext = CastContext.getSharedInstance(context);

  final MediaRouteButton button = new ColorableMediaRouteButton(context);
  googleCastButtonManagerInstance = button;

  CastButtonFactory.setUpMediaRouteButton(context, button);

  updateButtonState(button, castContext.getCastState());

  castContext.addCastStateListener(new CastStateListener() {
    @Override
    public void onCastStateChanged(int newState) {
      GoogleCastButtonManager.this.updateButtonState(button, newState);
    }
  });

  return button;
}
 
Example #4
Source File: QueueListAdapter.java    From CastVideos-android with Apache License 2.0 6 votes vote down vote up
private void updatePlayPauseButtonImageResource(ImageButton button) {
    CastSession castSession = CastContext.getSharedInstance(mAppContext)
            .getSessionManager().getCurrentCastSession();
    RemoteMediaClient remoteMediaClient =
            (castSession == null) ? null : castSession.getRemoteMediaClient();
    if (remoteMediaClient == null) {
        button.setVisibility(View.GONE);
        return;
    }
    int status = remoteMediaClient.getPlayerState();
    switch (status) {
        case MediaStatus.PLAYER_STATE_PLAYING:
            button.setImageResource(PAUSE_RESOURCE);
            break;
        case MediaStatus.PLAYER_STATE_PAUSED:
            button.setImageResource(PLAY_RESOURCE);
            break;
        default:
            button.setVisibility(View.GONE);
    }
}
 
Example #5
Source File: VideoBrowserActivity.java    From cast-videos-android with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.video_browser);
    setupActionBar();

    mCastStateListener = new CastStateListener() {
        @Override
        public void onCastStateChanged(int newState) {
            if (newState != CastState.NO_DEVICES_AVAILABLE) {
                showIntroductoryOverlay();
            }
        }
    };

    mCastContext = CastContext.getSharedInstance(this);
}
 
Example #6
Source File: VideoBrowserActivity.java    From CastVideos-android with Apache License 2.0 6 votes vote down vote up
@Override
protected void onResume() {
    mCastContext.addCastStateListener(mCastStateListener);
    mCastContext.getSessionManager().addSessionManagerListener(
            mSessionManagerListener, CastSession.class);
    intentToJoin();
    if (mCastSession == null) {
        mCastSession = CastContext.getSharedInstance(this).getSessionManager()
                .getCurrentCastSession();
    }
    if (mQueueMenuItem != null) {
        mQueueMenuItem.setVisible(
                (mCastSession != null) && mCastSession.isConnected());
    }
    super.onResume();
}
 
Example #7
Source File: VideoBrowserActivity.java    From CastVideos-android with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.video_browser);
    setupActionBar();

    mCastStateListener = new CastStateListener() {
        @Override
        public void onCastStateChanged(int newState) {
            if (newState != CastState.NO_DEVICES_AVAILABLE) {
                showIntroductoryOverlay();
            }
        }
    };
    mCastContext = CastContext.getSharedInstance(this);
}
 
Example #8
Source File: BaseActivity.java    From SkyTube with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onSessionStarted(Session session, String sessionId) {
	mCastSession = CastContext.getSharedInstance(BaseActivity.this).getSessionManager().getCurrentCastSession();
	invalidateOptionsMenu();
	YouTubePlayer.setConnectedToChromecast(true);
	YouTubePlayer.setConnectingToChromecast(false);
	// If we are connecting in YouTubePlayerActivity, finish that activity and launch the currently playing
	// video on the Chromecast.
	if(isLocalPlayer()) {
		returnToMainAndResume();
	} else if(externalPlayIntent != null) {
		// A default Chromecast has been set to handle external intents, and that Chromecast has now been
		// connected to. Play the video (which is stored in externalPlayIntent).
		handleExternalPlayOnChromecast(externalPlayIntent);
		externalPlayIntent = null;
	}
	if(notificationClickIntent != null) {
		handleNotificationClick(notificationClickIntent);
		notificationClickIntent = null;
	}
}
 
Example #9
Source File: BaseActivity.java    From SkyTube with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onSessionResumed(Session session, boolean wasSuspended) {
	mCastSession = CastContext.getSharedInstance(BaseActivity.this).getSessionManager().getCurrentCastSession();
	Runnable r = () -> {
		if(mCastSession.getRemoteMediaClient().getPlayerState() != MediaStatus.PLAYER_STATE_IDLE) {
			chromecastMiniControllerFragment.init(mCastSession.getRemoteMediaClient());
			chromecastControllerFragment.init(mCastSession.getRemoteMediaClient());
			slidingLayout.addPanelSlideListener(getOnPanelDisplayed((int) mCastSession.getRemoteMediaClient().getApproximateStreamPosition(), (int) mCastSession.getRemoteMediaClient().getStreamDuration()));
		} else if(externalPlayIntent != null) {
			// A default Chromecast has been set to handle external intents, and that Chromecast has now been
			// connected to. Play the video (which is stored in externalPlayIntent).
			handleExternalPlayOnChromecast(externalPlayIntent);
			externalPlayIntent = null;
		}
	};
	// Sometimes when we resume a chromecast session, even if media is actually playing, the player state is still idle here.
	// In that case, wait 500ms and check again (above Runnable). But if it's not idle, do the above right away.
	int delay = mCastSession.getRemoteMediaClient().getPlayerState() != MediaStatus.PLAYER_STATE_IDLE ? 0 : 500;
	new Handler().postDelayed(r, delay);

	invalidateOptionsMenu();
	YouTubePlayer.setConnectedToChromecast(true);
	YouTubePlayer.setConnectingToChromecast(false);
}
 
Example #10
Source File: TestUtils.java    From CastVideos-android with Apache License 2.0 6 votes vote down vote up
/**
 * Get Cast context and media status info
 */
void getCastInfo() {
    InstrumentationRegistry.getInstrumentation().runOnMainSync(
            new Runnable() {
                @Override
                public void run() {
                    mCastContext = CastContext.getSharedInstance(mTragetContext);
                    mSessionManager = mCastContext.getSessionManager();
                    mCastSession = mSessionManager.getCurrentCastSession();
                    if (mCastSession != null) {
                        mRemoteMediaClient = mCastSession.getRemoteMediaClient();
                        isCastConnected = mCastSession.isConnected();
                        if (mRemoteMediaClient != null) {
                            mMediaStatus = mRemoteMediaClient.getMediaStatus();
                        }
                    }
                }
            }
    );
}
 
Example #11
Source File: WatchLaterVideosFragment.java    From Loop with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    AccessToken token = LoopPrefs.getAccessToken(getActivity());
    vimeoService = ServiceGenerator.createService(
            VimeoService.class,
            VimeoService.BASE_URL,
            new AuthorizedNetworkInterceptor(token));

    setHasOptionsMenu(true);

    font = FontCache.getTypeface("Ubuntu-Medium.ttf", getContext());
    compositeSubscription = new CompositeSubscription();

    castContext = CastContext.getSharedInstance(getContext());
}
 
Example #12
Source File: LikedVideosFragment.java    From Loop with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getArguments() != null) {
        query = getArguments().getString("query");
    }

    AccessToken token = LoopPrefs.getAccessToken(getActivity());
    vimeoService = ServiceGenerator.createService(
            VimeoService.class,
            VimeoService.BASE_URL,
            new AuthorizedNetworkInterceptor(token));

    setHasOptionsMenu(true);

    font = FontCache.getTypeface("Ubuntu-Medium.ttf", getContext());

    compositeSubscription = new CompositeSubscription();

    castContext = CastContext.getSharedInstance(getContext());
}
 
Example #13
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setSupportActionBar((Toolbar) findViewById(R.id.toolbar));

    mListView = (ListView) findViewById(R.id.list);

    mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());

    mAdapter.add("Movie 1");
    mAdapter.add("Movie 2");
    mAdapter.add("Movie 3");
    mAdapter.add("Movie 4");
    mAdapter.add("Movie 5");
    mAdapter.add("Movie 6");
    mAdapter.add("Movie 7");

    mListView.setAdapter(mAdapter);
    mListView.setOnItemClickListener(this);

    CastContext.getSharedInstance(this).addCastStateListener(this);
    CastContext.getSharedInstance(this).addAppVisibilityListener(this);
    CastContext.getSharedInstance(this).getSessionManager().addSessionManagerListener(this);
}
 
Example #14
Source File: VideoDetailsFragment.java    From Loop with Apache License 2.0 5 votes vote down vote up
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        // Retain this fragment across configuration changes.
        setRetainInstance(true);

        if (getArguments() != null) {
            video = (Video) getArguments().get(LikedVideosFragment.KEY_VIDEO);
//            mTransitionName = getArguments().getString("TRANSITION_KEY");
        }

        AccessToken token = LoopPrefs.getAccessToken(getActivity());
        vimeoPlayerService = ServiceGenerator.createService(
                VimeoPlayerService.class,
                VimeoPlayerService.BASE_URL,
                new AuthorizedNetworkInterceptor(token));

        setHasOptionsMenu(true);

        font = FontCache.getTypeface("Ubuntu-Medium.ttf", getContext());

        castContext = CastContext.getSharedInstance(getContext());
        castSession = castContext.getSessionManager().getCurrentCastSession();

        playbackState = PlaybackState.PLAYING;

        if (castSession != null && castSession.isConnected()) {
            location = PlaybackLocation.REMOTE;
        } else {
            location = PlaybackLocation.LOCAL;
        }
    }
 
Example #15
Source File: CastPlayback.java    From klingar with Apache License 2.0 5 votes vote down vote up
CastPlayback(Context context) {
  appContext = context.getApplicationContext();
  CastSession castSession = CastContext.getSharedInstance(appContext).getSessionManager()
      .getCurrentCastSession();
  remoteMediaClient = castSession.getRemoteMediaClient();
  remoteMediaClientCallback = new CastMediaClientCallback();
}
 
Example #16
Source File: GoogleCastDelegate.java    From edx-app-android with Apache License 2.0 5 votes vote down vote up
private void init() {
    // TODO: Replace the try-catch block with more appropriate logic so Travis-ci build get passed.
    // Can't get CastContext instance while executing test cases of "CourseUnitNavigationActivityTest"
    // and throw exception.
    try {
        castContext = CastContext.getSharedInstance(this.context);
        castSession = castContext.getSessionManager().getCurrentCastSession();
        castContext.getSessionManager().addSessionManagerListener(this,
                CastSession.class);
        registerRemoteCallback();
    } catch (Exception ignore) {
    }
}
 
Example #17
Source File: MusicService.java    From klingar with Apache License 2.0 5 votes vote down vote up
@Override public int onStartCommand(Intent startIntent, int flags, int startId) {
  if (startIntent != null) {
    if (ACTION_STOP_CASTING.equals(startIntent.getAction())) {
      CastContext.getSharedInstance(this).getSessionManager().endCurrentSession(true);
    } else {
      // Try to handle the intent as a media button event wrapped by MediaButtonReceiver
      MediaButtonReceiver.handleIntent(session, startIntent);
    }
  }
  // Reset the delay handler to enqueue a message to stop the service if nothing is playing
  delayedStopHandler.removeCallbacksAndMessages(null);
  delayedStopHandler.sendEmptyMessageDelayed(0, STOP_DELAY);
  return START_STICKY;
}
 
Example #18
Source File: MusicService.java    From klingar with Apache License 2.0 5 votes vote down vote up
@Override public void onCreate() {
  super.onCreate();
  Timber.d("onCreate");
  KlingarApp.get(this).component().inject(this);

  Playback playback = new LocalPlayback(getApplicationContext(), musicController, audioManager,
      wifiManager, client);
  playbackManager = new PlaybackManager(queueManager, this, AndroidClock.DEFAULT, playback);

  session = new MediaSessionCompat(this, "MusicService");

  try {
    MediaControllerCompat mediaController =
        new MediaControllerCompat(this.getApplicationContext(), session.getSessionToken());
    musicController.setMediaController(mediaController);
  } catch (RemoteException e) {
    Timber.e(e, "Could not create MediaController");
    throw new IllegalStateException();
  }

  session.setCallback(playbackManager.getMediaSessionCallback());

  Context context = getApplicationContext();
  Intent intent = new Intent(context, KlingarActivity.class);
  session.setSessionActivity(PendingIntent.getActivity(context, 99, intent, FLAG_UPDATE_CURRENT));

  playbackManager.updatePlaybackState();

  mediaNotificationManager = new MediaNotificationManager(this, musicController,
      queueManager, rx);

  castSessionManager = CastContext.getSharedInstance(this).getSessionManager();
  castSessionManagerListener = new CastSessionManagerListener();
  castSessionManager.addSessionManagerListener(castSessionManagerListener, CastSession.class);

  mediaRouter = MediaRouter.getInstance(getApplicationContext());

  timelineManager = new TimelineManager(musicController, queueManager, media, rx);
  timelineManager.start();
}
 
Example #19
Source File: BaseController.java    From klingar with Apache License 2.0 5 votes vote down vote up
@NonNull @Override
protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
  injectDependencies();
  View view = inflater.inflate(getLayoutResource(), container, false);
  unbinder = ButterKnife.bind(this, view);
  if (getActivity() != null) {
    if (toolbar != null) {
      ((KlingarActivity) getActivity()).setSupportActionBar(toolbar);
    }
    castContext = CastContext.getSharedInstance(getActivity());
  }
  return view;
}
 
Example #20
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
@Override
protected void onDestroy() {
    super.onDestroy();
    CastContext.getSharedInstance(this).removeAppVisibilityListener(this);
    CastContext.getSharedInstance(this).removeCastStateListener(this);
    CastContext.getSharedInstance(this).getSessionManager().removeSessionManagerListener(this);
}
 
Example #21
Source File: GoogleCastModule.java    From react-native-google-cast with MIT License 5 votes vote down vote up
@Override
public void onHostPause() {
    getReactApplicationContext().runOnUiQueueThread(new Runnable() {
        @Override
        public void run() {
            SessionManager sessionManager =
                    CastContext.getSharedInstance(getReactApplicationContext())
                            .getSessionManager();
            sessionManager.removeSessionManagerListener(mSessionManagerListener,
                    CastSession.class);
        }
    });
}
 
Example #22
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
    if( CastContext.getSharedInstance(this).getSessionManager().getCurrentCastSession() != null
            && CastContext.getSharedInstance(this).getSessionManager().getCurrentCastSession().getRemoteMediaClient() != null ) {

        RemoteMediaClient remoteMediaClient = CastContext.getSharedInstance(this).getSessionManager().getCurrentCastSession().getRemoteMediaClient();


        if( remoteMediaClient.getMediaInfo() != null &&
                remoteMediaClient.getMediaInfo().getMetadata() != null
                && mAdapter.getItem(position).equalsIgnoreCase(
                    remoteMediaClient.getMediaInfo().getMetadata().getString(MediaMetadata.KEY_TITLE))) {

            startActivity(new Intent(this, ExpandedControlsActivity.class));

        } else {
            MediaMetadata metadata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MOVIE);

            metadata.putString(MediaMetadata.KEY_TITLE, mAdapter.getItem(position));
            metadata.putString(MediaMetadata.KEY_SUBTITLE, "Subtitle");
            metadata.addImage(new WebImage(Uri.parse(getString(R.string.movie_poster))));
            metadata.addImage(new WebImage(Uri.parse(getString(R.string.movie_poster))));

            MediaInfo mediaInfo = new MediaInfo.Builder(getString(R.string.movie_link))
                    .setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
                    .setContentType("videos/mp4")
                    .setMetadata(metadata)
                    .build();


            remoteMediaClient.load(mediaInfo, true, 0);
        }
    } else {
        startActivity(new Intent(this, MovieDetailActivity.class));
    }
}
 
Example #23
Source File: GoogleCastModule.java    From react-native-google-cast with MIT License 5 votes vote down vote up
@Override
public void onHostResume() {
    getReactApplicationContext().runOnUiQueueThread(new Runnable() {
        @Override
        public void run() {
            SessionManager sessionManager =
                    CastContext.getSharedInstance(getReactApplicationContext())
                            .getSessionManager();
            sessionManager.addSessionManagerListener(mSessionManagerListener,
                    CastSession.class);
        }
    });
}
 
Example #24
Source File: GoogleCastModule.java    From react-native-google-cast with MIT License 5 votes vote down vote up
public static void initializeCast(Context context){
    try {
        CastContext.getSharedInstance(context);
    } catch(RuntimeException e) {
        CAST_AVAILABLE = false;
    }
}
 
Example #25
Source File: VinylCastApplication.java    From vinyl-cast with MIT License 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    // This static call will reset default values only on the first ever read. Also according
    // to StrictMode, it's slow due to disk reads on Main Thread.
    PreferenceManager.setDefaultValues(getBaseContext(), R.xml.preferences, false);

    // get Cast session manager here in Application as according to StrictMode it's slow due to
    // performing disk reads on Main Thread and only needs to be fetched once anyway.
    castSessionManager = CastContext.getSharedInstance(this).getSessionManager();

    NativeAudioEngine.create();
}
 
Example #26
Source File: QueueListViewActivity.java    From CastVideos-android with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.queue_activity);
    Log.d(TAG, "onCreate() was called");

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new QueueListViewFragment(), FRAGMENT_LIST_VIEW)
                .commit();
    }
    setupActionBar();
    mEmptyView = findViewById(R.id.empty);
    mCastContext = CastContext.getSharedInstance(this);
}
 
Example #27
Source File: GoogleCastModule.java    From react-native-google-cast with MIT License 5 votes vote down vote up
@ReactMethod
public void getCastState(final Promise promise) {
    getReactApplicationContext().runOnUiQueueThread(new Runnable() {
        @Override
        public void run() {
            if (CAST_AVAILABLE) {
                CastContext castContext =
                    CastContext.getSharedInstance(getReactApplicationContext());
                promise.resolve(castContext.getCastState() - 1);
            } else {
                promise.reject(E_CAST_NOT_AVAILABLE, GOOGLE_CAST_NOT_AVAILABLE_MESSAGE);
            }
        }
    });
}
 
Example #28
Source File: QueueListViewFragment.java    From CastVideos-android with Apache License 2.0 5 votes vote down vote up
private RemoteMediaClient getRemoteMediaClient() {
    CastSession castSession =
            CastContext.getSharedInstance(getContext()).getSessionManager()
                    .getCurrentCastSession();
    if (castSession != null && castSession.isConnected()) {
        return castSession.getRemoteMediaClient();
    }
    return null;
}
 
Example #29
Source File: QueueListViewFragment.java    From CastVideos-android with Apache License 2.0 5 votes vote down vote up
private void onContainerClicked(View view) {
    RemoteMediaClient remoteMediaClient = getRemoteMediaClient();
    if (remoteMediaClient == null) {
        return;
    }
    MediaQueueItem item = (MediaQueueItem) view.getTag(R.string.queue_tag_item);
    if (mProvider.isQueueDetached()) {
        Log.d(TAG, "Is detached: itemId = " + item.getItemId());

        int currentPosition = mProvider.getPositionByItemId(item.getItemId());
        MediaQueueItem[] items = Utils.rebuildQueue(mProvider.getItems());
        remoteMediaClient.queueLoad(items, currentPosition,
                MediaStatus.REPEAT_MODE_REPEAT_OFF, null);
    } else {
        int currentItemId = mProvider.getCurrentItemId();
        if (currentItemId == item.getItemId()) {
            // We selected the one that is currently playing so we take the user to the
            // full screen controller
            CastSession castSession = CastContext.getSharedInstance(
                    getContext().getApplicationContext())
                    .getSessionManager().getCurrentCastSession();
            if (castSession != null) {
                Intent intent = new Intent(getActivity(), ExpandedControlsActivity.class);
                startActivity(intent);
            }
        } else {
            // a different item in the queue was selected so we jump there
            remoteMediaClient.queueJumpToItem(item.getItemId(), null);
        }
    }
}
 
Example #30
Source File: QueueDataProvider.java    From CastVideos-android with Apache License 2.0 5 votes vote down vote up
private RemoteMediaClient getRemoteMediaClient() {
    CastSession castSession = CastContext.getSharedInstance(mAppContext).getSessionManager()
            .getCurrentCastSession();
    if (castSession == null || !castSession.isConnected()) {
        Log.w(TAG, "Trying to get a RemoteMediaClient when no CastSession is started.");
        return null;
    }
    return castSession.getRemoteMediaClient();
}