I'm trying to load a VAST ad using Exoplayer IMA extension (using tutorials 1, 2). I want to keep ad and content progress, so if app goes background or screen rotates, user continues from the point he/she was watching. You can see my code here and main codes below for convenience. (Duo to some limitations, I'm stuck with version 2.9.6 of Exoplayer library)
public class MainActivity extends AppCompatActivity {
private PlayerView playerView;
private SimpleExoPlayer player;
private static final String KEY_WINDOW = "window";
private int currentWindow;
private static final String KEY_POSITION = "position";
private long playbackPosition;
private static final String KEY_AUTO_PLAY = "auto_play";
private boolean playWhenReady;
private ImaAdsLoader adsLoader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playerView = findViewById(R.id.exo_video_view);
if (adsLoader == null)
adsLoader = new ImaAdsLoader(this, Uri.parse(getString(R.string.ad_tag_url)));
if (savedInstanceState != null) {
currentWindow = savedInstanceState.getInt(KEY_WINDOW);
playbackPosition = savedInstanceState.getLong(KEY_POSITION);
playWhenReady = savedInstanceState.getBoolean(KEY_AUTO_PLAY, true);
}
}
private MediaSource buildMediaSource(Uri uri, DataSource.Factory dataSourceFactory) {
return new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
}
private MediaSource buildAdMediaSource(MediaSource contentMediaSource, DataSource.Factory dataSourceFactory){
// Create the AdsMediaSource using the AdsLoader and the MediaSource.
return new AdsMediaSource(contentMediaSource, dataSourceFactory, adsLoader, playerView);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
}
private void initializePlayer() {
player = ExoPlayerFactory.newSimpleInstance(this);
playerView.setPlayer(player);
if (adsLoader != null)
adsLoader.setPlayer(player);
Uri contentUri = Uri.parse(getString(R.string.media_url_mp4));
DataSource.Factory dataSourceFactory =
new DefaultDataSourceFactory(this, "exoplayer-codelab");
MediaSource contentMediaSource = buildMediaSource(contentUri, dataSourceFactory);
MediaSource adMediaSource = buildAdMediaSource(contentMediaSource, dataSourceFactory);
player.setPlayWhenReady(playWhenReady);
player.seekTo(currentWindow, playbackPosition);
player.prepare(adMediaSource, false, false);
}
#Override
public void onStart() {
super.onStart();
if (Util.SDK_INT >= 24) {
initializePlayer();
if (playerView != null) {
playerView.onResume();
}
}
}
#Override
public void onResume() {
super.onResume();
hideSystemUi();
if ((Util.SDK_INT < 24 || player == null)) {
initializePlayer();
if (playerView != null) {
playerView.onResume();
}
}
}
private void hideSystemUi() {
playerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
#Override
public void onPause() {
super.onPause();
if (Util.SDK_INT < 24) {
if (playerView != null) {
playerView.onPause();
}
releasePlayer();
}
}
#Override
public void onStop() {
super.onStop();
if (Util.SDK_INT >= 24) {
if (playerView != null) {
playerView.onPause();
}
releasePlayer();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseAdsLoader();
}
private void releasePlayer() {
if (player != null) {
updateStartPosition();
player.release();
player = null;
}
if (adsLoader != null) {
adsLoader.setPlayer(null);
}
}
private void releaseAdsLoader() {
if (adsLoader != null) {
adsLoader.release();
adsLoader = null;
if (playerView.getOverlayFrameLayout() != null)
playerView.getOverlayFrameLayout().removeAllViews();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
updateStartPosition();
outState.putBoolean(KEY_AUTO_PLAY, playWhenReady);
outState.putInt(KEY_WINDOW, currentWindow);
outState.putLong(KEY_POSITION, playbackPosition);
}
private void updateStartPosition() {
if (player != null) {
playWhenReady = player.getPlayWhenReady();
currentWindow = player.getCurrentWindowIndex();
playbackPosition = Math.max(0, player.getContentPosition());
}
}
}
Problem is, when screen rotates, activity fields like ImaAdsLoader becomes null and ad and content video play from start. I've saved player progress and can successfully restore it's position but that's not case for ImaAdsLoader since I couldn't find a way to restore its state. Am I doing anything wrong? How Ad progress state should be saved and restored?
A common pattern with video players is to prevent your activity from being recreated with orientation changes so you should add these flags to your manifest.
android:configChanges="keyboardHidden|orientation|screenSize"
This would also prevent the surface view that shows your video from being destroyed with orientation changes too.
The README.md of the Exoplayer IMA extension is quite clear about this:
You need to persist a reference to the ImaAdsLoader. When recreating the view pass that reference back when AdsLoaderProvider.getAdsLoader(MediaItem.AdsConfiguration adsConfiguration) is called.
Additionally, persist the player position when the view gets destroyed by storing the value of player.getContentPosition(). After recreation seek that position before preparing the new player instance.
You can find an example in the Exoplayer's demo app's PlayerActivity.java.
Related
I want implement next and previous buttons below the ExoPlayer. I'm basing my code on this thread:
Implementing next button in audio player android
and the links in these ones:
How to add Listener for next , previous , rewind and forward in Exoplayer
How to add next song and previous song play button in audio player using android studio2.3?
The Exoplayer is in a fragment and opens on the right side of the screen on a tablet screen and in a separate activity on a mobile screen when the user clicks on one of the recipe steps. Data to the StepsFragment(implements an onClickListener) is sent via parcelable from the parent activity(code below).
Next and previous buttons are only implemented on the mobile screen(code works fine). I'm passing the arraylist and position from the parent activity in the onClick method and retrieving them in the fragment. The code works fine w/o the buttons, and both the list and the position are sent via parcelable to the VideoFragment only to implement the buttons. I decided to put the buttons in the Video Fragment.
Nothing happens when clicking on either the next or previous button. Code flow is indicated in the comments above the code in the onClickListener. I've tried to debug but no errors are displayed. Is this the right way to pass the arraylist? Although it's not shown in the debug and the log cat, I think it might be null. Can someone please have a look? Thank you in advance.
VideoFragment(contains Exoplayer code):
public class VideoFragment extends Fragment
{
// Tag for logging
private static final String TAG = VideoFragment.class.getSimpleName();
/**
* Mandatory empty constructor for the fragment manager to instantiate the fragment
*/
public VideoFragment()
{
}
ArrayList<Steps> stepsArrayList;
Steps stepClicked;
Recipes recipes;
SimpleExoPlayer mExoPlayer;
#BindView(R.id.playerView)
SimpleExoPlayerView mPlayerView;
#BindView(R.id.thumbnail_url)
ImageView thumbnailUrlImage;
public int stepPosition;
private long mPlayerPosition;
String videoUrl;
Uri videoUrl_Parse;
Uri thumbnailUrl_Parse;
String thumbnailUrl;
#BindView(R.id.previous_button)
Button previousButton;
#BindView(R.id.next_button)
Button nextButton;
#BindView(R.id.step_long_description)
TextView stepLongDescription;
String stepLongDescriptionUrl;
boolean mTwoPane;
private static final String KEY_POSITION = "position";
public static final String STEPS_LIST_INDEX = "list_index";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//Inflate the Steps fragment layout
View rootView = inflater.inflate(R.layout.fragment_video, container, false);
// Bind the views
ButterKnife.bind(this, rootView);
Bundle bundle = this.getArguments();
if (bundle != null)
{
//Track whether to display a two-pane or single-pane UI
stepClicked = getArguments().getParcelable("Steps");
if (stepClicked != null)
{
mTwoPane = getArguments().getBoolean("TwoPane");
stepPosition = getArguments().getInt("StepPosition");
stepsArrayList = getArguments().getParcelableArrayList("StepsArrayList");
stepsArrayList = new ArrayList<>();
videoUrl = stepClicked.getVideoUrl();
Log.i("VideoUrl: ", stepClicked.getVideoUrl());
videoUrl_Parse = Uri.parse(videoUrl);
thumbnailUrl = stepClicked.getThumbnailUrl();
thumbnailUrl_Parse = Uri.parse(thumbnailUrl);
stepLongDescriptionUrl = stepClicked.getStepLongDescription();
Log.i("Step: ", stepClicked.getStepLongDescription());
stepLongDescription.setText(stepLongDescriptionUrl);
if (thumbnailUrl != null)
{
Picasso.with(getContext())
.load(thumbnailUrl_Parse)
.into(thumbnailUrlImage);
}
}
if (mTwoPane)
{
previousButton.setVisibility(View.INVISIBLE);
nextButton.setVisibility(View.INVISIBLE);
} else
{
previousButton.setVisibility(View.VISIBLE);
nextButton.setVisibility(View.VISIBLE);
//https://stackoverflow.com/questions/45253477/implementing-next-button-in-audio-player-android
nextButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (stepPosition < stepsArrayList.size() - 1)
{
//Add or subtract the position in 1
stepClicked= stepsArrayList.get(stepPosition);
stepPosition++;
//Using the position, get the current step from the steps list
stepClicked= stepsArrayList.get(stepPosition);
//Extract the video uri from the current step
videoUrl = stepClicked.getVideoUrl();
Log.d("VideoUrlNext: ", stepClicked.getVideoUrl());
videoUrl_Parse = Uri.parse(videoUrl);
//Call initializePlayer() by passing the new video uri
initializePlayer(videoUrl_Parse);
}
}
});
previousButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (stepPosition> 0)
{
stepPosition--;
//Using the position, get the current step from the steps list
stepClicked= stepsArrayList.get(stepPosition);
//Extract the video uri from the current step
videoUrl = stepClicked.getVideoUrl();
videoUrl_Parse = Uri.parse(videoUrl);
//Call initializePlayer() by passing the new video uri
initializePlayer(videoUrl_Parse);
}
}
});
}
}
if (savedInstanceState != null)
{
stepsArrayList = savedInstanceState.getParcelableArrayList(STEPS_LIST_INDEX);
mPlayerPosition = savedInstanceState.getLong(KEY_POSITION);
}
// Return the root view
return rootView;
}
//ExoPlayer code based on: https://codelabs.developers.google.com/codelabs/exoplayer-intro/#2
public void initializePlayer(Uri videoUrl)
{
if (mExoPlayer == null)
{
TrackSelector trackSelector = new DefaultTrackSelector();
LoadControl loadControl = new DefaultLoadControl();
mExoPlayer = ExoPlayerFactory.newSimpleInstance(getActivity(), trackSelector, loadControl);
mPlayerView.setPlayer((SimpleExoPlayer) mExoPlayer);
String userAgent = Util.getUserAgent(getContext(), "Baking App");
MediaSource mediaSource = new ExtractorMediaSource(videoUrl,
new DefaultDataSourceFactory(getContext(), userAgent),
new DefaultExtractorsFactory(), null, null);
mExoPlayer.prepare(mediaSource);
if (mPlayerPosition != C.TIME_UNSET)
{
mExoPlayer.seekTo(mPlayerPosition);
}
mExoPlayer.setPlayWhenReady(true);
}
}
#Override
public void onStart()
{
super.onStart();
if (Util.SDK_INT > 23 || mExoPlayer == null)
{
initializePlayer(videoUrl_Parse);
}
}
#Override
public void onPause()
{
super.onPause();
if (mExoPlayer != null)
{
mPlayerPosition = mExoPlayer.getCurrentPosition();
}
if (Util.SDK_INT <= 23)
{
releasePlayer();
}
}
#Override
public void onResume()
{
super.onResume();
if ((Util.SDK_INT <= 23 || mExoPlayer == null))
{
mPlayerPosition = mExoPlayer.getCurrentPosition();
}
}
#Override
public void onStop()
{
super.onStop();
if (Util.SDK_INT > 23 || mExoPlayer != null)
{
mExoPlayer.getCurrentPosition();
}
releasePlayer();
}
/**
* Release ExoPlayer.
*/
private void releasePlayer()
{
if (mExoPlayer != null)
{
mPlayerPosition = mExoPlayer.getCurrentPosition();
mExoPlayer.release();
mExoPlayer = null;
}
}
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
//Save the fragment's state here
outState.putParcelableArrayList(STEPS_LIST_INDEX, stepsArrayList);
outState.putLong(KEY_POSITION, mPlayerPosition);
super.onSaveInstanceState(outState);
}
}
Parent Activity:
public class IngredientStepsActivity extends AppCompatActivity implements StepsListFragment.OnStepClickListener
{
private static final String TAG = IngredientStepsActivity.class.getSimpleName();
private Context context;
Recipes recipes;
// Track whether to display a two-pane or single-pane UI
public boolean mTwoPane;
public int stepPosition;
ArrayList<Steps> stepsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ingredientsteps);
// Determine if you're creating a two-pane or single-pane display
if (savedInstanceState == null)
{
if (getIntent() != null && getIntent().getExtras() != null)
{
recipes = getIntent().getExtras().getParcelable("Recipes");
if(findViewById(R.id.tablet_detail_layout) != null)
{
// This LinearLayout will only initially exist in the two-pane tablet case
mTwoPane = true;
// Only create new fragments when there is no previously saved state
/*
Add the fragment to its container using a FragmentManager and a Transaction
Send the ingredients array list in Parcelable to the Ingredients Fragment
*/
FragmentManager fragmentManager = getSupportFragmentManager();
Bundle ingredientsBundle = new Bundle();
ingredientsBundle.putParcelable("Recipes", recipes);
//Pass Over the bundle to the Ingredients Fragment
IngredientsFragment ingredientsFragment = new IngredientsFragment();
ingredientsFragment.setArguments(ingredientsBundle);
fragmentManager.beginTransaction().replace(R.id.ingredients_fragment_container, ingredientsFragment).commit();
//Pack Data in a bundle call the bundle "stepsBundle" to differentiate it from the "ingredientsBundle"
Bundle stepsBundle = new Bundle();
stepsBundle.putParcelable("Recipes", recipes);
//Pass Over the bundle to the Steps Fragment
StepsListFragment stepsListFragment = new StepsListFragment();
stepsListFragment.setArguments(stepsBundle);
fragmentManager.beginTransaction().replace(R.id.steps_fragment_container, stepsListFragment).commit();
}
else
{
// We're in single-pane mode and displaying fragments on a phone in separate activities
mTwoPane = false;
FragmentManager fragmentManager = getSupportFragmentManager();
Bundle ingredientsBundle = new Bundle();
ingredientsBundle.putParcelable("Recipes", recipes);
//Pass Over the bundle to the Ingredients Fragment
IngredientsFragment ingredientsFragment = new IngredientsFragment();
ingredientsFragment.setArguments(ingredientsBundle);
fragmentManager.beginTransaction().replace(R.id.ingredients_fragment_container, ingredientsFragment).commit();
//Pack Data in a bundle call the bundle "stepsBundle" to differentiate it from the "ingredientsBundle"
Bundle stepsBundle = new Bundle();
stepsBundle.putParcelable("Recipes", recipes);
//Pass Over the bundle to the Steps Fragment
StepsListFragment stepsListFragment = new StepsListFragment();
stepsListFragment.setArguments(stepsBundle);
fragmentManager.beginTransaction().replace(R.id.steps_fragment_container, stepsListFragment).commit();
}
}
}}
#Override
public void onClick(Steps stepClicked)
{
if (mTwoPane)
{
Bundle stepsVideoBundle = new Bundle();
stepsVideoBundle.putParcelable("Steps", stepClicked);
stepsVideoBundle.putBoolean("TwoPane", mTwoPane);
stepsVideoBundle.putInt("StepPosition", stepPosition);
stepsVideoBundle.putParcelableArrayList("StepsArrayList", stepsArrayList);
VideoFragment videoFragment = new VideoFragment();
videoFragment.setArguments(stepsVideoBundle);
getSupportFragmentManager().beginTransaction().replace(R.id.video_fragment_container, videoFragment).commit();
}
else
{
Log.i("Step: ", stepClicked.getStepShortDescription());
Intent intent = new Intent(IngredientStepsActivity.this, VideoPhoneActivity.class);
intent.putExtra("Steps", stepClicked);
startActivity(intent);
}
}
}
My aim is to show several video at one Activity at the same time using ExoPlayer 2. (I got hls source for each video). I'm succesfully play one video. So I decided to make implementation of the Player inside Fragment and create new Fragment for each hls sources to put them inside Activity. But only one Fragment succesfully playing video, other Fragments looks like black square without any content. How to resolve it?
I'm using ExoPlayer 2.7.2 .
My Activity code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Bundle bundle1 = new Bundle();
bundle1.putString(SmallPlayerfragment.VIDEO_KEY, SmallPlayerfragment.Source1);
Bundle bundle2 = new Bundle();
bundle2.putString(SmallPlayerfragment.VIDEO_KEY, SmallPlayerfragment.Source2);
Fragment fragment1 = new SmallPlayerfragment();
fragment1.setArguments(bundle1);
Fragment fragment2 = new SmallPlayerfragment();
fragment2.setArguments(bundle2);
if (getSupportFragmentManager().findFragmentByTag(SmallPlayerfragment.TAG1) == null
| getSupportFragmentManager().findFragmentByTag(SmallPlayerfragment.TAG2) == null)
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.test_container, fragment2, SmallPlayerfragment.TAG2)
.replace(R.id.bottom_test_container, fragment1, SmallPlayerfragment.TAG1)
.commit();
}
My Fragment code
public class SmallPlayerfragment extends Fragment {
String mVideoURL;
public final static String VIDEO_KEY = "videoKey";
public final static String Source2 = "source2";
public final static String Source1 = "source1";
public final static String TAG1 = "fragment_1";
public final static String TAG2 = "fragment_2";
PlayerView mPlayerView;
SimpleExoPlayer mPlayer;
public SmallPlayerfragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_small_player, container, false);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mPlayerView = getActivity().findViewById(R.id.small_player);
if (getArguments() != null) {
mVideoURL = getArguments().getString(VIDEO_KEY);
} else {
mVideoURL = Source1;
}
}
#Override
public void onStart() {
super.onStart();
Log.d("test", "onStart Fragment");
if (Util.SDK_INT > 23) {
initializePlayer();
}
}
#Override
public void onResume() {
super.onResume();
Log.d("test", "onResume Fragment");
// hideSystemUi();
if ((Util.SDK_INT <= 23 || mPlayer == null)) {
initializePlayer();
}
}
#Override
public void onPause() {
Log.d("test", "onPause Fragment");
super.onPause();
if (Util.SDK_INT <= 23) {
releasePlayer();
}
}
#Override
public void onStop() {
Log.d("test", "onStop Fragment");
super.onStop();
if (Util.SDK_INT > 23) {
releasePlayer();
}
}
#SuppressLint("InlinedApi")
private void hideSystemUi() {
mPlayerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
private void initializePlayer() {
mPlayer = ExoPlayerFactory.newSimpleInstance(
new DefaultRenderersFactory(getContext()),
new DefaultTrackSelector(), new DefaultLoadControl());
mPlayerView.setPlayer(mPlayer);
mPlayer.seekTo(0);
Uri uri = Uri.parse(mVideoURL);
MediaSource mediaSource = buildMediaSource(uri);
mPlayer.prepare(mediaSource, true, false);
mPlayer.setPlayWhenReady(true);
}
private MediaSource buildMediaSource(Uri uri) {
// Measures bandwidth during playback. Can be null if not required.
DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
// Produces DataSource instances through which media data is loaded.
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(getContext(),
Util.getUserAgent(getContext(), "yourApplicationName"), bandwidthMeter);
// This is the MediaSource representing the media to be played.
MediaSource videoSource = new HlsMediaSource.Factory(dataSourceFactory)
.createMediaSource(uri);
// Prepare the player with the source.
return videoSource;
}
private void releasePlayer() {
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
I think its just a focus issue. The fragment needs to be in focus to play video.
Also in your Exoplayer fragment drop a little if to check for focus before playing the video.
The fragment in focus should only play the video.
The issue is that there is a delay when I try to change the orientation of the player. There is a lag of some 2 or 3 seconds before the video resumes. Every thing else works just fine except for the orientation change.
public class MainActivity extends AppCompatActivity {
private final String STATE_RESUME_WINDOW = "resumeWindow";
private final String STATE_RESUME_POSITION = "resumePosition";
private final String STATE_PLAYER_FULLSCREEN = "playerFullscreen";
private SimpleExoPlayerView mExoPlayerView;
private MediaSource mVideoSource;
private boolean mExoPlayerFullscreen = false;
private FrameLayout mFullScreenButton;
private ImageView mFullScreenIcon;
private Dialog mFullScreenDialog;
private int mResumeWindow;
private long mResumePosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
mResumeWindow = savedInstanceState.getInt(STATE_RESUME_WINDOW);
mResumePosition = savedInstanceState.getLong(STATE_RESUME_POSITION);
mExoPlayerFullscreen = savedInstanceState.getBoolean(STATE_PLAYER_FULLSCREEN);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(STATE_RESUME_WINDOW, mResumeWindow);
outState.putLong(STATE_RESUME_POSITION, mResumePosition);
outState.putBoolean(STATE_PLAYER_FULLSCREEN, mExoPlayerFullscreen);
super.onSaveInstanceState(outState);
}
private void initFullscreenDialog() {
mFullScreenDialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen) {
public void onBackPressed() {
if (mExoPlayerFullscreen)
closeFullscreenDialog();
super.onBackPressed();
}
};
}
private void openFullscreenDialog() {
((ViewGroup) mExoPlayerView.getParent()).removeView(mExoPlayerView);
mFullScreenDialog.addContentView(mExoPlayerView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
mFullScreenIcon.setImageDrawable(ContextCompat.getDrawable(MainActivity.this,R.drawable.ic_fullscreen_shrink));
mExoPlayerFullscreen = true;
mFullScreenDialog.show();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
private void closeFullscreenDialog() {
((ViewGroup) mExoPlayerView.getParent()).removeView(mExoPlayerView);
((FrameLayout) findViewById(R.id.main_media_frame)).addView(mExoPlayerView);
mExoPlayerFullscreen = false;
mFullScreenDialog.dismiss();
mFullScreenIcon.setImageDrawable(ContextCompat.getDrawable(MainActivity.this,R.drawable.ic_fullscreen_expand));
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
private void initFullscreenButton() {
PlaybackControlView controlView = mExoPlayerView.findViewById(R.id.exo_controller);
mFullScreenIcon = controlView.findViewById(R.id.exo_fullscreen_icon);
mFullScreenButton = controlView.findViewById(R.id.exo_fullscreen_button);
mFullScreenButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mExoPlayerFullscreen)
openFullscreenDialog();
else
closeFullscreenDialog();
}
});
}
private void initExoPlayer() {
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
LoadControl loadControl = new DefaultLoadControl();
SimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(new DefaultRenderersFactory(this),trackSelector, loadControl);
mExoPlayerView.setPlayer(player);
boolean haveResumePosition = mResumeWindow != C.INDEX_UNSET;
if (haveResumePosition) {
mExoPlayerView.getPlayer().seekTo(mResumeWindow, mResumePosition);
}
mExoPlayerView.getPlayer().prepare(mVideoSource);
mExoPlayerView.getPlayer().setPlayWhenReady(true);
}
#Override
protected void onResume() {
super.onResume();
if (mExoPlayerView == null) {
mExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.exoplayer);
initFullscreenDialog();
initFullscreenButton();
String streamUrl = "https://mnmedias.api.telequebec.tv/m3u8/29880.m3u8";
String userAgent = Util.getUserAgent(MainActivity.this, getApplicationContext().getApplicationInfo().packageName);
DefaultHttpDataSourceFactory httpDataSourceFactory = new DefaultHttpDataSourceFactory(userAgent, null,
DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS,
DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS, true);
DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(MainActivity.this, null,httpDataSourceFactory);
Uri daUri = Uri.parse(streamUrl);
mVideoSource = new HlsMediaSource(daUri, dataSourceFactory, 1, null, null);
}
initExoPlayer();
if (mExoPlayerFullscreen) {
((ViewGroup) mExoPlayerView.getParent()).removeView(mExoPlayerView);
mFullScreenDialog.addContentView(mExoPlayerView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
mFullScreenIcon.setImageDrawable(ContextCompat.getDrawable(MainActivity.this,
R.drawable.ic_fullscreen_shrink));
mFullScreenDialog.show();
}
}
#Override
protected void onPause() {
super.onPause();
if (mExoPlayerView != null && mExoPlayerView.getPlayer() != null) {
mResumeWindow = mExoPlayerView.getPlayer().getCurrentWindowIndex();
mResumePosition = Math.max(0, mExoPlayerView.getPlayer().getContentPosition());
mExoPlayerView.getPlayer().release();
}
if (mFullScreenDialog != null)
mFullScreenDialog.dismiss();
}
}
You should look into handling configuration changes yourself - as #marcbaechinger mentions above.
The necessary piece is here:
<activity android:name=".MyActivity"
android:configChanges="orientation|screenSize"
android:label="#string/app_name">
The most important part is:
Remember: When you declare your activity to handle a configuration change, you are responsible for resetting any elements for which you provide alternatives. If you declare your activity to handle the orientation change and have images that should change between landscape and portrait, you must re-assign each resource to each element during onConfigurationChanged().
But if you don't have any landscape specific layout files or images, then you'll likely be okay.
We had to write our own full screen logic for rotation, but that's simple enough considering Android gives you the configuration change event.
And to tack on a little extra validity to this approach, it's recommended by Google via the Youtube player documentation (specifically in regards to fullscreen):
To achieve this for an activity that supports portrait, you need to specify that your activity handles some configuration changes on its own in your application's manifest, including orientation, keyboardHidden and screenSize.
I'm using this example code to build a MediaPlayer Service. I have it more or less working, however if a user returns to the Activity that contains the media controls, I need to detect what state the MediaPlayer is in. The code I'm currently using throws a NullReferenceException error in onResume because getPlaybackState() is always null.
I'm new to using MediaSessionCompat and according to the documentation, I can get the current session somehow:
"Once a session is created the owner of the session may pass its session token to other processes to allow them to create a MediaControllerCompat to interact with the session."
public class MediaActivity extends AppCompatActivity {
private MediaBrowserCompat mMediaBrowserCompat;
private MediaControllerCompat mMediaControllerCompat;
private Activity mActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_media);
mActivity = this;
mPlayButton = (Button)findViewById(R.id.btn_play);
mMediaBrowserCompat = new MediaBrowserCompat(
getApplicationContext(),
new ComponentName(mContext, MediaPlayerService.class),
mMediaBrowserCompatConnectionCallback,
getIntent().getExtras()
);
mMediaBrowserCompat.connect();
mPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if( mCurrentState == STATE_PAUSED ) {
getSupportMediaController().getTransportControls().play();
mCurrentState = STATE_PLAYING;
mPlayButton.setText("Pause");
} else {
MediaControllerCompat.getMediaController(mActivity).getTransportControls().pause();
mCurrentState = STATE_PAUSED;
mPlayButton.setText("Play");
}
}
});
#Override
public void onResume() {
super.onResume();
if (MediaControllerCompat.getMediaController(mActivity).getPlaybackState().getState() == PlaybackStateCompat.STATE_PLAYING) {
mPlayButton.setText("Pause")
}
else{
mPlayButton.setText("Play")
}
}
private MediaBrowserCompat.ConnectionCallback mMediaBrowserCompatConnectionCallback = new MediaBrowserCompat.ConnectionCallback() {
#Override
public void onConnected() {
super.onConnected();
try {
mMediaControllerCompat = new MediaControllerCompat(PodcastEpisodeActivity.this, mMediaBrowserCompat.getSessionToken());
mMediaControllerCompat.registerCallback(mMediaControllerCompatCallback);
MediaControllerCompat.setMediaController(mActivity, mMediaControllerCompat);
MediaControllerCompat.getMediaController(mActivity).getTransportControls().playFromUri(Uri.parse("http://www.url.com"), extras);
} catch( RemoteException e ) {
Log.e(mActivity.getPackageName(), e.toString());
}
}
};
private MediaControllerCompat.Callback mMediaControllerCompatCallback = new MediaControllerCompat.Callback() {
#Override
public void onPlaybackStateChanged(PlaybackStateCompat state) {
super.onPlaybackStateChanged(state);
if (state == null ) return;
switch (state.getState()) {
case PlaybackStateCompat.STATE_PLAYING: {
mCurrentState = STATE_PLAYING;
break;
}
case PlaybackStateCompat.STATE_PAUSED: {
mCurrentState = STATE_PAUSED;
break;
}
}
}
};
}
}
I couldn't figure out a way through the available API, so I'm just tracking which media is being played through local storage (sqlite) and updating the display through that. Probably not the most elegant solution but it works.
I am using XWalkView to show a mobile web site as an application. My problem is when application goes background and comes back it reloads the page it shows. I want to keep it state and continue from that state when it comes from background. Here is my code:
public class MainActivity extends AppCompatActivity {
static final String URL = "https://www.biletdukkani.com.tr";
static final int MY_PERMISSIONS_REQUEST_ACCESS_LOCATION = 55;
static final String SHOULD_ASK_FOR_LOCATION_PERMISSION = "shouldAskForLocationPermission";
static final String TAG = "MainActivity";
static final String COMMAND = "/system/bin/ping -c 1 185.22.184.184";
static XWalkView xWalkWebView;
TextView noInternet;
static Bundle stateBundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
stateBundle = savedInstanceState.getBundle("xwalk");
}
setContentView(R.layout.activity_main);
initNoInternetTextView();
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
stateBundle = savedInstanceState.getBundle("xwalk");
Log.d(TAG, "onRestoreInstanceState");
}
/**
* İnternet yok mesajı gösteren TextVidew'i ayarlar.
*/
private void initNoInternetTextView() {
Log.d(TAG, "initNoInternetTextView");
noInternet = (TextView) findViewById(R.id.no_internet);
if (noInternet != null) {
noInternet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkInternetConnection();
}
});
}
}
/**
* WebView'i ayarlar.
*/
private void initWebView() {
Log.d(TAG, "initWebView");
if (xWalkWebView == null) {
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
xWalkWebView = (XWalkView) findViewById(R.id.webView);
//xWalkWebView.clearCache(true);
xWalkWebView.load(URL, null);
xWalkWebView.setResourceClient(new BDResourceClient(xWalkWebView, progressBar));
}
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
checkLocationPermissions();
checkInternetConnection();
if (xWalkWebView != null && stateBundle != null) {
xWalkWebView.restoreState(stateBundle);
}
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause");
if (xWalkWebView != null) {
stateBundle = new Bundle();
xWalkWebView.saveState(stateBundle);
}
}
public void onSaveInstanceState(Bundle savedInstanceState) {
Log.d(TAG, "onSaveInstanceState");
// Save the user's current game state
savedInstanceState.putBundle("xwalk", stateBundle);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onBackPressed() {
Log.d(TAG, "onBackPressed");
if (xWalkWebView != null && xWalkWebView.getNavigationHistory().canGoBack()) {
xWalkWebView.getNavigationHistory().navigate(XWalkNavigationHistory.Direction.BACKWARD, 1);
} else {
super.onBackPressed();
}
}
}
I have also tried to add following lines to manifest but didn't work.
android:launchMode="singleTask"
android:alwaysRetainTaskState="true"
How can i do that?
Thanks in advcance.
One way would be to initialize the view inside a fragment which is set to retain it's instance.