It takes too long to start a video and in the console I get this error again and again until the video finally start:
I/NuPlayerRenderer: possible video time jump of 0ms or uninitialized media clock, retrying in 100ms
Here is my Activity class:
public class EntryView extends AppCompatActivity implements SurfaceHolder.Callback {
SurfaceView imageLogo;
MediaPlayer mp;
#Override
protected void attachBaseContext(Context newBase) {
ContextWrapper contextWrapper = CalligraphyContextWrapper.wrap(newBase);
super.attachBaseContext(contextWrapper);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
overridePendingTransition(0, 0);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entry);
imageLogo = (SurfaceView) findViewById(R.id.image_logo);
imageLogo.getHolder().addCallback(this);
mp = new MediaPlayer();
ButterKnife.bind(this);
}
// UI CALLBACKS ------------------------------------------------------------------------------
#OnClick({R.id.button_login, R.id.button_register_normal})
void openScreen(View v) {
Intent intent = null;
switch (v.getId()) {
case R.id.button_login:
intent = new Intent(EntryView.this, LoginView.class);
break;
case R.id.button_register_normal:
intent = new Intent(EntryView.this, RegisterView.class);
break;
}
startActivity(intent);
overridePendingTransition(R.anim.slide_in_from_right, R.anim.scale_out);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Uri video = Uri.parse("android.resource://" + getPackageName() + "/"
+ R.raw.sample);
try {
mp.setDataSource(this, video);
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
//Get the dimensions of the video
int videoWidth = mp.getVideoWidth();
int videoHeight = mp.getVideoHeight();
//Get the width of the screen
int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
//Get the SurfaceView layout parameters
android.view.ViewGroup.LayoutParams lp = imageLogo.getLayoutParams();
//Set the width of the SurfaceView to the width of the screen
lp.width = screenWidth;
//Set the height of the SurfaceView to match the aspect ratio of the video
//be sure to cast these as floats otherwise the calculation will likely be 0
lp.height = (int) (((float)videoHeight / (float)videoWidth) * (float)screenWidth);
//Commit the layout parameters
imageLogo.setLayoutParams(lp);
//Start video
mp.setDisplay(holder);
mp.setLooping(true);
mp.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
And this is the xml file:
<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.omnidoctor.omniapp.screens.entry.EntryView">
<SurfaceView
android:id="#+id/image_logo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dip"/>
<View
android:id="#+id/spacer"
android:layout_marginTop="85dp"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_heightPercent="20%" />
<Button
android:id="#+id/button_register_normal"
fontPath="fonts/Arciform.ttf"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/spacer"
android:background="#drawable/background_button_white"
android:minHeight="20dp"
android:paddingBottom="20dp"
android:paddingTop="20dp"
android:text="#string/register_normal_text"
android:textAllCaps="false"
android:textColor="#color/state_color_blue"
android:textSize="16sp"
app:layout_marginLeftPercent="10%"
app:layout_marginRightPercent="10%"
tools:ignore="MissingPrefix" />
<Button
android:id="#+id/button_login"
fontPath="fonts/Arciform.ttf"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#id/button_register_normal"
android:layout_marginTop="14dp"
android:minHeight="20dp"
android:minWidth="0dp"
android:textColor="#color/state_color_blue"
android:background="#drawable/background_button_white"
android:paddingBottom="20dp"
android:paddingTop="20dp"
android:text="#string/log_in"
android:textAllCaps="false"
android:textSize="15sp"
app:layout_marginLeftPercent="10%"
app:layout_marginRightPercent="10%"
tools:ignore="MissingPrefix" />
</android.support.percent.PercentRelativeLayout>
As you can see I am using a SurfaceView but I tried as well with VideoView and I get the same problem. The video just have 1,5MB for and it takes 30 seconds so it is not a really big one.
EDIT
I forgot to tell that is a mp4 video. I am not sure if this has something to do but just in case.
Hi I'm trying to achieve an Activity with background made from video file. The solution posted below is working on most devices, except nexus 6 Android 5.1. The video is working, is scaled but is not cropped, so aspect ratio is not preserved.
Tested with Galaxy Note, HTC One m7, Xperia Z3, Nexus 5.
Here is the code:
public class MainActivity extends ActionBarActivity implements SurfaceHolder.Callback, OnClickListener
{
private static final int VIDEO_START_HACK_DELAY = 0;
private static final String BG_VIDEO_PATH = "/raw/construction";
private SurfaceView mSurface;
private Button mTour, mLogin;
private MediaPlayer mMediaPlayer;
private Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_main);
setupUI();
}
private void setupUI()
{
mMediaPlayer = new MediaPlayer();
mSurface = (SurfaceView) findViewById(R.id.surface);
SurfaceHolder holder = mSurface.getHolder();
holder.addCallback(this);
mTour = (Button) findViewById(R.id.tour);
mLogin = (Button) findViewById(R.id.login);
mTour.setOnClickListener(this);
mLogin.setOnClickListener(this);
}
#Override
public void surfaceCreated(SurfaceHolder holder)
{
startVideo(holder);
}
#SuppressLint("NewApi")
public void startVideo(SurfaceHolder holder)
{
String path = "android.resource://" + getPackageName() + BG_VIDEO_PATH;
Uri uri = Uri.parse(path);
try
{
android.view.ViewGroup.LayoutParams lp = mSurface.getLayoutParams();
mMediaPlayer.setDisplay(holder);
mMediaPlayer.setDataSource(this, uri);
mMediaPlayer.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
mMediaPlayer.setLooping(true);
mMediaPlayer.setOnPreparedListener(new OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mHandler.postDelayed(new Runnable()
{
#Override
public void run()
{
mMediaPlayer.start();
}
}, VIDEO_START_HACK_DELAY);
}
});
mMediaPlayer.prepareAsync();
}
catch (Exception e)
{
Log.e("VID", "Problem starting video bg", e);
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
// TODO Auto-generated method stub
}
#Override
public void onBackPressed()
{
mSurface.setVisibility(View.INVISIBLE);
mMediaPlayer.stop();
super.onBackPressed();
}
#Override
protected void onDestroy()
{
mMediaPlayer.stop();
mMediaPlayer.release();
super.onDestroy();
}
}
Here is layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<SurfaceView
android:id="#+id/surface"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="40dp"
android:gravity="center"
android:orientation="vertical" >
<Button
android:id="#+id/tour"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:padding="10dp"
android:text="#string/ma_tour"/>
<Button
android:id="#+id/login"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:padding="10dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:text="#string/ma_log_in"/>
</LinearLayout>
</RelativeLayout>
Target sdk is set to 22.
Have you maybe experienced such behavior and can give any advice?
Here is how I did it in one of my applications:
Set the OnPreparedListener on MediaPlayer object.
mediaPlayer.setOnPreparedListener(this);
When the public void onPrepared(MediaPlayer mp) is called, resize the SurfaceView so that it creates the illusion of cropped video.
Log.v(LOG_TAG, "onPrepared called for MediaPlayer");
// Adjust the size of the video so it fits on the screen
int videoWidth = mInitialVideoPlayer.getVideoWidth();
int videoHeight = mInitialVideoPlayer.getVideoHeight();
float videoProportion = (float) videoWidth / (float) videoHeight;
ViewGroup.LayoutParams lp = mSplashVideoSurfaceView.getLayoutParams();
// We always want to fill entire view port. So, we keep the smallest dimension and proportionately
// scale the other dimension.
if (videoWidth < videoHeight) {
lp.width = UiUtils.sScreenWidth;
lp.height = (int) ((float) UiUtils.sScreenWidth / videoProportion);
} else {
lp.width = (int) (videoProportion * (float) UiUtils.sScreenHeight);If you are targetting API level 14 and above, <code>TextureView</code> allows you to play cropped video
lp.height = UiUtils.sScreenHeight;
}
Log.v(LOG_TAG, "old video size: " + videoWidth + ", " + videoHeight);
Log.v(LOG_TAG, "screen size: " + UiUtils.sScreenWidth + ", " + UiUtils.sScreenHeight);
Log.v(LOG_TAG, "new video size: " + lp.width + ", " + lp.height);
mSplashVideoSurfaceView.setLayoutParams(lp);
I am trying to make use of MediaPlayer class for playing a video file. The problem is video is not getting displayed at all though I can hear the sound in the video playing.
Following is the code of activity
public class MainActivity extends Activity implements OnClickListener {
private SurfaceView surfaceView;
private Button btnPlay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
addListener();
}
private void init() {
// TODO Auto-generated method stub
surfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
btnPlay = (Button) findViewById(R.id.btnPlay);
}
private void addListener() {
// TODO Auto-generated method stub
btnPlay.setOnClickListener(this);
}
MediaPlayer mediaPlayer = null;
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnPlay:
try{
if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.release();
}else{
getWindow().setFormat(PixelFormat.UNKNOWN);
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.wildlife);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
surfaceHolder.setFixedSize(176, 144);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.start();}
}catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
}
Following is the code of layout xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<SurfaceView
android:id="#+id/surfaceView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
<Button
android:id="#+id/btnPlay"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/surfaceView1"
android:layout_alignTop="#+id/surfaceView1"
android:text="#string/play" />
</RelativeLayout>
please tell me what needs to be done?
Thanks in advance.
You can override the onSizeChanged() function of the SurfaceView class to get and set the size of the view.
protected void onSizeChanged (int w, int h, int oldw, int oldh)
When ever the screen size has changed, this class is called.
As a second alternative, you may be able to set the size by setting the layout parameters (unsure if this works with ScrollView):
#Override
public void surfaceCreated(SurfaceHolder holder) {
android.view.ViewGroup.LayoutParams lp = this.getLayoutParams();
lp.width = 1000; // required width
lp.height = 1000; // required height
this.setLayoutParams(lp);
}
set surface View height and width to fill parent in xml file.
<SurfaceView
android:id="#+id/surfaceView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
Setting your SurfaceView layout to wrap_content will not size a video to play at the proper aspect ratio.
You can refer to this answer link
https://stackoverflow.com/a/6283676/1441666
And also this blog Play media on surfaceview using android.media.MediaPlayer
Well, I don't know if you need an specific situation, but have you already tried FullscreenVideoView?
It tries to abstracts all those SurfaceView problems and you can focus only in UI buttons. As It's open, you can subclass FullscreenVideoView and customize as you need.
i have a videoview in my application. the code is like this.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/opsbuds"
android:orientation="vertical">
<TextView
android:id="#+id/adtxt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"></TextView>
<VideoView
android:id="#+id/videoView11"
android:layout_width="300dip"
android:layout_height="250dip"
android:layout_marginLeft="30dip"></VideoView>
<LinearLayout
android:id="#+id/llv11"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"></LinearLayout>
<Button
android:id="#+id/button1211"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:background="#drawable/button"
android:text=" Continue "
android:textColor="#800080"
android:textSize="20dp"
android:textStyle="bold"></Button>
</LinearLayout>
</ScrollView>
the video view width and hieght is mentioned in xml file. What i want is , once i press a button the videoview should come on full screen and once i press back button the videoview should go back to its mentioned size. please help?
I had to make my VideoView sit in a RelativeLayout in order to make the chosen answer work.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<VideoView android:id="#+id/videoViewRelative"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</VideoView>
</RelativeLayout>
As given here: Android - How to stretch video to fill VideoView area Toggling between screen sizes would be as simple as changing the layout parameters as given in the chosen answer.
Set full screen this way,
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
android.widget.LinearLayout.LayoutParams params = (android.widget.LinearLayout.LayoutParams) videoView.getLayoutParams();
params.width = metrics.widthPixels;
params.height = metrics.heightPixels;
params.leftMargin = 0;
videoView.setLayoutParams(params);
And back to original size, this way.
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
android.widget.LinearLayout.LayoutParams params = (android.widget.LinearLayout.LayoutParams) videoView.getLayoutParams();
params.width = (int)(300*metrics.density);
params.height = (int)(250*metrics.density);
params.leftMargin = 30;
videoView.setLayoutParams(params);
I have done this way:
Check these reference screen shots.
Add class FullScreenVideoView.java:
import android.content.Context;
import android.util.AttributeSet;
import android.widget.VideoView;
public class FullScreenVideoView extends VideoView {
public FullScreenVideoView(Context context) {
super(context);
}
public FullScreenVideoView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FullScreenVideoView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
}
}
How to bind with xml:
<FrameLayout
android:id="#+id/secondMedia"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.my.package.customview.FullScreenVideoView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fullScreenVideoView"/>
</FrameLayout>
Hope this will help you.
First Method
when you want to open a video in full screen for that Activity you have to set the theme attribute in the Manifest. set this value that is
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
change theme programmatically here
Second Method
create another fullscreen.xml like below and setContentView(R.layout.fullscreen) on click of the button
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<VideoView android:id="#+id/myvideoview"
android:layout_width="fill_parent"
android:layout_alignParentRight="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_height="fill_parent">
</VideoView>
</RelativeLayout>
On Button click start the native video player which will open in full screen:
Intent intent = new Intent(Intent.ACTION_VIEW );
intent.setDataAndType(Uri.parse(path), "video/*");
startActivity(intent);
The below code worked.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
Add this code before calling videoView.start(). With this the video activity runs in full screen mode in most of the cases. But if the title bar is still displayed then change your theme in your manifest to this.
android:theme="#style/Theme.AppCompat.NoActionBar">
you can achieve it by creating two separate activity.
Suppose first activity is halfScreen activity. In this activity your video view having small size. On button click of full screen video start another activity 'fullScreen activity'. In second activity the video view should be match parent to the parent layout.you can also start video in full screen from where it is paused in half screen.In my code i have implemented that.Also you can resume the video in half screen on the back press of fullscreen activity.
This is work for me.Hope it will work for you also.
Here is the code
half.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#aa99cc"
android:orientation="vertical" >
<VideoView
android:id="#+id/VideoViewhalf"
android:layout_width="match_parent"
android:layout_height="300dp" >
</VideoView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/btnfullScreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fullscreen" />
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
HalfScreen activity
public class HalfScreen extends Activity {
Button btn;
VideoView videoView = null;
final int REQUEST_CODE = 5000;
final String videoToPlay = "http://bffmedia.com/bigbunny.mp4";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.half);
videoView = (VideoView) findViewById(R.id.VideoViewhalf);
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
btn = (Button) findViewById(R.id.btnfullScreen);
Uri video = Uri.parse(videoToPlay);
videoView.setVideoURI(video);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
progressBar.setVisibility(View.GONE);
videoView.requestFocus();
videoView.start();
}
});
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent videointent = new Intent(HalfScreen.this,
FullScreen.class);
videointent.putExtra("currenttime",
videoView.getCurrentPosition());
videointent.putExtra("Url", videoToPlay);
startActivityForResult(videointent, REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
if (data.hasExtra("currenttime")) {
int result = data.getExtras().getInt("currenttime", 0);
if (result > 0) {
if (null != videoView) {
videoView.start();
videoView.seekTo(result);
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
}
}
}
}
}
}
full.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff99cc"
android:orientation="vertical" >
<VideoView
android:id="#+id/VideoViewfull"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</VideoView>
</LinearLayout>
FullScreen Activity
public class FullScreen extends Activity {
Button btn;
VideoView videoView = null;
int currenttime = 0;
String Url = "";
private static ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (null != extras) {
currenttime = extras.getInt("currenttime", 0);
Url = extras.getString("Url");
}
setContentView(R.layout.full);
progressDialog = ProgressDialog.show(this, "", "Loading...", true);
videoView = (VideoView) findViewById(R.id.VideoViewfull);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
Uri video = Uri.parse(Url);
videoView.setMediaController(mediaController);
videoView.setVideoURI(video);
videoView.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer arg0) {
progressDialog.dismiss();
videoView.start();
videoView.seekTo(currenttime);
}
});
}
#Override
public void finish() {
Intent data = new Intent();
data.putExtra("currenttime", videoView.getCurrentPosition());
setResult(RESULT_OK, data);
super.finish();
}
}
I achieved it by switching to landscape orientation and setting layout params to MATCH_PARENT. Just before switching to fullscreen mode, we need to store current orientation mode and VideoView params indefaultScreenOrientationMode and defaultVideoViewParams variables correspondingly. So that we can use them when we exit from video fullscreen mode. Thus, when you want to open video in fullscreen mode, use makeVideoFullScreen() method, to exit - exitVideoFullScreen().
Please, note I used RelativeLayout for my VideoView, in your case it can be another layout type.
private RelativeLayout.LayoutParams defaultVideoViewParams;
private int defaultScreenOrientationMode;
// play video in fullscreen mode
private void makeVideoFullScreen() {
defaultScreenOrientationMode = getResources().getConfiguration().orientation;
defaultVideoViewParams = (LayoutParams) videoView.getLayoutParams();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
videoView.postDelayed(new Runnable() {
#Override
public void run() {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
videoView.setLayoutParams(params);
videoView.layout(10, 10, 10, 10);
}
}, 700);
}
// close fullscreen mode
private void exitVideoFullScreen() {
setRequestedOrientation(defaultScreenOrientationMode);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
videoView.postDelayed(new Runnable() {
#Override
public void run() {
videoView.setLayoutParams(defaultVideoViewParams);
videoView.layout(10, 10, 10, 10);
}
}, 700);
}
whether you want to keep the aspect ratio of a video or stretch it to fill its parent area, using the right layout manager can get the job done.
Keep the aspect ratio :
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<VideoView
android:id="#+id/videoView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"/>
</LinearLayout>
!!! To fill in the field:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<VideoView android:id="#+id/videoViewRelative"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</VideoView>
</RelativeLayout>
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
android.widget.LinearLayout.LayoutParams params = (android.widget.LinearLayout.LayoutParams) mVideoView.getLayoutParams();
params.width = (int) metrics.widthPixels;
params.height = (int) metrics.heightPixels;
mVideoView.setLayoutParams(params);
playVideo();
aspectRatio = VideoInfo.AR_4_3_FIT_PARENT;
mVideoView.getPlayer().aspectRatio(aspectRatio);
Try code below here.
if (!isFullScreen())
{
Log.v("Full screen", "-----------is full screen------------");
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
android.widget.FrameLayout.LayoutParams params = (android.widget.FrameLayout.LayoutParams) videoSurface.getLayoutParams();
params.width = width;
params.height=height;
params.setMargins(0, 0, 0, 0);
}
else{
Log.v("Full screen", "-----------small screen------------");
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
android.widget.FrameLayout.LayoutParams params = (android.widget.FrameLayout.LayoutParams) videoSurface.getLayoutParams();
params.width = width;
params.height=height / 3;
params.setMargins(0, 0, 0, 0);
}
This code is for full screen landscape video
AndroidManifext.xml (Setting the orientation)
<activity
android:name=".Video1"
android:screenOrientation="landscape" />
Video1.java Code :
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;
import android.widget.MediaController;
import android.widget.VideoView;
public class Video1 extends AppCompatActivity {
private VideoView videoView;
private MediaController mediaController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video1);
videoView = findViewById(R.id.videoView);
String fullScreen = getIntent().getStringExtra("fullScreenInd");
if("y".equals(fullScreen)){
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
}
Uri videoUri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.YOUR_VIDEO_NAME);
videoView.setVideoURI(videoUri);
mediaController = new FullScreenMediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.start();
}
}
FullScreenMediaControler.java Code :
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.MediaController;
public class FullScreenMediaController extends MediaController {
private ImageButton fullScreen;
private String isFullScreen;
public FullScreenMediaController(Context context) {
super(context);
}
#Override
public void setAnchorView(View view) {
super.setAnchorView(view);
//image button for full screen to be added to media controller
fullScreen = new ImageButton (super.getContext());
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.RIGHT;
params.rightMargin = 80;
addView(fullScreen, params);
//fullscreen indicator from intent
isFullScreen = ((Activity)getContext()).getIntent().
getStringExtra("fullScreenInd");
if("y".equals(isFullScreen)){
fullScreen.setImageResource(R.drawable.ic_fullscreen_exit);
}else{
fullScreen.setImageResource(R.drawable.ic_fullscreen);
}
//add listener to image button to handle full screen and exit full screen events
fullScreen.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(),Video1.class);
if("y".equals(isFullScreen)){
intent.putExtra("fullScreenInd", "");
}else{
intent.putExtra("fullScreenInd", "y");
}
((Activity)getContext()).startActivity(intent);
}
});
}
}
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".auth.fragments.SplashScreenFragment">
<VideoView
android:id="#+id/video_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
I'm positioning a VideoView with AbsoluteLayout (I need to display it on several places into the screen at specific positions).
public void showVideo(RectF bounds, final String videoUrl) {
AbsoluteLayout.LayoutParams params = (AbsoluteLayout.LayoutParams) video.getLayoutParams();
params.width = (int) bounds.width();
params.height = (int) bounds.height();
params.x = (int) bounds.left;
params.y = (int) bounds.top;
video.requestLayout();
video.setVisibility(View.VISIBLE);
video.setFocusable(true);
video.setFocusableInTouchMode(true);
video.requestFocus();
File file = new File(videoUrl);
video.setVideoPath(file.getAbsolutePath());
video.start();
}
But the Video ins't getting resized to the bounds I specified.
Any tips?
Another related question is, how to make the MediaController show over the VideoView?
this is very close to what you are trying. if you are willing to subclass the videoview and override onMeasure here is the solution. you need to
MyVideoView extends VideoView
https://stackoverflow.com/questions/4434027/android-videoview-orientation-change-with-buffered-video/4452597#4452597
as for showing MediaController over VidowView
Declare
private MediaController controller = null;
OnCreate
controller = new MediaController(this);
controller.setMediaPlayer(mcEvents);
controller.setAnchorView(findViewById(R.id.wrapper));
Activity
#Override
public boolean onTouchEvent(MotionEvent event) {
//the MediaController will hide after 3 seconds - tap the screen to make it appear again
controller.show();
return false;
}
Media Controller events
private MediaController.MediaPlayerControl mcEvents = new MediaController.MediaPlayerControl() {
public void start() {
player.start();
}
public void seekTo(int pos) {
player.seekTo(pos);
}
public void pause() {
player.pause();
}
public boolean isPlaying() {
return player.isPlaying();
}
public int getDuration() {
return player.getDuration();
}
public int getCurrentPosition() {
return player.getCurrentPosition();
}
public int getBufferPercentage() {
return pBuffer;
}
public boolean canSeekForward() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canPause() {
return true;
}
};
a sample layout file
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/wrapper"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.my.views.MyViedoView
android:id="#+id/player"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</FrameLayout>
You can only change the layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<VideoView android:id="#+id/videoViewRelative"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</VideoView>
</RelativeLayout>
After you change your LayoutParams I think you will need to call setLayoutParams so the layout can be updated with the new params. After the call to setLayoutParams you may have to call the method reqestLayout to invalidate the layout and trigger a redraw of the view.
You will need to create a new instance of the MediaController and use the method setMediaController on the VideoView object.