Как воспроизвести рекламу перед видео через Chromecast с помощью IMA SDK?
Я разрабатываю потоковое приложение, в котором реализована функциональность Chromecast. Все работает нормально, но единственная проблема заключается в том, что у видео с контентом есть реклама до ролика, либо пропускается реклама, а видео контента воспроизводится, если мы подключились к Chromecast, или реклама локально Проигрывается и после этого контент-видео воспроизводится через chromecast. Мой вопрос: можем ли мы воспроизводить как рекламу, так и контент-видео через chromecast, используя IMA SDK, потому что вручную это возможно, и я сделал это, но с IMA SDK не повезло. Мой код выглядит так:
public class ClassChromeCast {
Context context;
public ClassChromeCast(Context ctx){
context = ctx;
}
/**
* Chromecast
* */
private static final String TAG = "MainActivity";
public MediaRouter mMediaRouter;
public static MediaRouteSelector mMediaRouteSelector;
public MediaRouter.Callback mMediaRouterCallback;
private CastDevice mSelectedDevice;
private GoogleApiClient mApiClient;
private RemoteMediaPlayer mRemoteMediaPlayer;
private Cast.Listener mCastClientListener;
public static boolean mIsPlaying,mIsFinished,mApplicationStarted = false,mVideoIsLoaded,isConnected = false;
private boolean mWaitingForReconnect = false,temp = false,temp2 = false;
/**
* Local variable
*/
private static String videoUrl = "",videoTitle = "" ,videoAdUrl = "";
private RSSFeed_Addsplay rssFeed_AddsplayObj;
/*======================Chromecast=======================*/
public void initMediaRouter() {
// Configure Cast device discovery
mMediaRouter = MediaRouter.getInstance(context);
mMediaRouteSelector = new MediaRouteSelector.Builder()
.addControlCategory( CastMediaControlIntent.categoryForCast( context.getString( R.string.app_id ) ) )
.build();
mMediaRouterCallback = new MediaRouterCallback();
}
/**inner class MediaRouterCallback **/
private class MediaRouterCallback extends MediaRouter.Callback {
@Override
public void onRouteSelected(MediaRouter router, MediaRouter.RouteInfo info) {
Log.d(TAG, "onRouteSelected");
initCastClientListener();
initRemoteMediaPlayer();
mSelectedDevice = CastDevice.getFromBundle( info.getExtras() );
launchReceiver();
}
@Override
public void onRouteUnselected( MediaRouter router, MediaRouter.RouteInfo info ) {
Log.d(TAG, "onRouteUnselected");
//teardown();
mSelectedDevice = null;
//isConnected = false;
//mVideoIsLoaded = false;
}
}
/**---------------to initialize CastClientListener---------------*/
private void initCastClientListener() {
mCastClientListener = new Cast.Listener() {
@Override
public void onApplicationStatusChanged() {
Log.d(TAG, "onApplicationStatusChanged");
}
@Override
public void onVolumeChanged() {
Log.d(TAG, "onVolumeChanged");
}
@Override
public void onApplicationDisconnected( int statusCode ) {
Log.d(TAG, "onApplicationDisconnected");
teardown();
}
};
}
/**---------------to initialize RemoteMediaPlayer---------------*/
private void initRemoteMediaPlayer() {
mRemoteMediaPlayer = new RemoteMediaPlayer();
mRemoteMediaPlayer.setOnStatusUpdatedListener( new RemoteMediaPlayer.OnStatusUpdatedListener() {
@Override
public void onStatusUpdated() {
try{
MediaStatus mediaStatus = mRemoteMediaPlayer.getMediaStatus();
mIsPlaying = mediaStatus.getPlayerState() == MediaStatus.PLAYER_STATE_PLAYING;
mIsFinished = mediaStatus.getPlayerState() == MediaStatus.PLAYER_STATE_IDLE;
Log.d(TAG,"IsPlaying==="+mIsPlaying+"IsFinished===="+mIsFinished);
if(mIsFinished && temp && !temp2){
//temp = false;
Log.e("startVideo2","===");
startVideo(videoUrl,videoTitle);
temp2 = true;
}
if(mIsPlaying){
temp = true;
}
}catch (Exception e){
e.printStackTrace();
}
}
});
mRemoteMediaPlayer.setOnMetadataUpdatedListener( new RemoteMediaPlayer.OnMetadataUpdatedListener() {
@Override
public void onMetadataUpdated() {
Log.d(TAG,"====mIsFinished");
}
});
}
private void launchReceiver() {
Cast.CastOptions.Builder apiOptionsBuilder = Cast.CastOptions
.builder( mSelectedDevice, mCastClientListener );
GoogleApiClient.ConnectionCallbacks mConnectionCallbacks = new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
Log.d(TAG,"Connected");
isConnected = true;
if( mWaitingForReconnect ) {
mWaitingForReconnect = false;
reconnectChannels( bundle );
} else {
try {
Cast.CastApi.launchApplication(mApiClient,context.getString(R.string.app_id), false)
.setResultCallback(new ResultCallback<Cast.ApplicationConnectionResult>() {
@Override
public void onResult(Cast.ApplicationConnectionResult applicationConnectionResult) {
Status status = applicationConnectionResult.getStatus();
if (status.isSuccess()) {
mApplicationStarted = true;
reconnectChannels(null);
}
}
}
);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onConnectionSuspended(int i) {
Log.e(TAG,"onConnectionSuspended");
isConnected = false;
mWaitingForReconnect = true;
}
};
GoogleApiClient.OnConnectionFailedListener mConnectionFailedListener = new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed");
isConnected = false;
teardown();
}
};
mApiClient = new GoogleApiClient.Builder(context)
.addApi( Cast.API, apiOptionsBuilder.build() )
.addConnectionCallbacks( mConnectionCallbacks )
.addOnConnectionFailedListener( mConnectionFailedListener )
.build();
mApiClient.connect();
}
private void reconnectChannels( Bundle hint ) {
if( ( hint != null ) && hint.getBoolean( Cast.EXTRA_APP_NO_LONGER_RUNNING ) ) {
Log.e( TAG, "App is no longer running" );
Log.d(TAG, "reconnectChannels");
teardown();
} else {
try {
Cast.CastApi.setMessageReceivedCallbacks( mApiClient, mRemoteMediaPlayer.getNamespace(), mRemoteMediaPlayer );
} catch( IOException e ) {
Log.e( TAG, "Exception while creating media channel ", e );
} catch( NullPointerException e ) {
Log.e( TAG, "Something wasn't reinitialized for reconnectChannels" );
}catch (IllegalStateException e){
e.printStackTrace();
}
}
}
public void teardown() {
if( mApiClient != null ) {
if( mApplicationStarted ){
try {
Cast.CastApi.stopApplication( mApiClient );
if( mRemoteMediaPlayer != null ) {
Cast.CastApi.removeMessageReceivedCallbacks( mApiClient, mRemoteMediaPlayer.getNamespace() );
mRemoteMediaPlayer = null;
}
} catch( Exception e ) {
Log.e( TAG, "Exception while removing application " + e );
}
mApplicationStarted = false;
}
if( mApiClient.isConnected() )
mApiClient.disconnect();
mApiClient = null;
}
mSelectedDevice = null;
mVideoIsLoaded = false;
}
/**----to play video remotely-----*/
public void playOnRemoteMediaPlayer(String title,String url, String adUrl){
Log.e("OnRemoteMediaPlayer","adUrl=="+adUrl);
try{
rssFeed_AddsplayObj = new RSSFeed_Addsplay(adUrl + System.currentTimeMillis());
videoAdUrl = rssFeed_AddsplayObj.getAdUrl();
}catch (Exception e){
videoAdUrl = "";
}
if(!mVideoIsLoaded && !videoUrl.equals(url)){
videoUrl = url;
videoTitle = title;
temp2 = false;
temp = false;
if (videoAdUrl != null && videoAdUrl.length() > 0){
Log.e("IF","===");
startVideo(videoAdUrl,"Your program begin after this ad break");
} else {
Log.e("ELSE","===");
startVideo(videoUrl,videoTitle);
}
//playPauseBtn.setImageResource(R.drawable.ic_av_pause_over_video_large);
} else {
controlVideo(videoUrl,videoTitle);
if(mIsPlaying){
//playPauseBtn.setImageResource(R.drawable.ic_av_play_over_video_large);
}else {
//playPauseBtn.setImageResource(R.drawable.ic_av_pause_over_video_large);
}
}
}
private void startVideo(String url, String s) {
Log.e(TAG,"===startVideo"+url);
TVE_HomeActivity.tvVideoLoadingText.setText(context.getString(R.string.playtext));
MediaMetadata mediaMetadata = new MediaMetadata( MediaMetadata.MEDIA_TYPE_MOVIE );
mediaMetadata.putString( MediaMetadata.KEY_TITLE,s);
MediaInfo mediaInfo = new MediaInfo.Builder(url)
.setContentType("video/mp4")
.setStreamType( MediaInfo.STREAM_TYPE_BUFFERED )
.setMetadata( mediaMetadata )
.build();
try {
mRemoteMediaPlayer.load( mApiClient, mediaInfo, true )
.setResultCallback( new ResultCallback<RemoteMediaPlayer.MediaChannelResult>() {
@Override
public void onResult( RemoteMediaPlayer.MediaChannelResult mediaChannelResult ) {
if( mediaChannelResult.getStatus().isSuccess() ) {
mVideoIsLoaded = true;
}
}
});
} catch( Exception e ) {
isConnected = false;
e.printStackTrace();
}
}
private void controlVideo(String url, String title) {
TVE_HomeActivity.tvVideoLoadingText.setText(context.getString(R.string.pausetext));
try{
if( mRemoteMediaPlayer == null || !mVideoIsLoaded )
return;
if( mIsPlaying ) {
mRemoteMediaPlayer.pause( mApiClient );
} else if(mIsFinished){
Log.d(TAG,"Finished===true");
startVideo(url,title);
} else {
mRemoteMediaPlayer.play( mApiClient );
}
Log.d(TAG,"running==="+mIsFinished);
}catch (Exception e){
e.printStackTrace();
}
}
}