在方向更改时重新创建 activity 时,媒体播放器不加载
media player does not load when activity is recreated on orientation change
我不熟悉使用表面视图在视频播放器中播放视频,现在我想保存媒体播放器的实例状态,当方向改变时,当视图重新加载或重新创建时,旧媒体播放器状态从旧位置开始,而不是加载到原始位置意味着在零位置我在清单中设置屏幕方向但那个时候oncreate没有被调用我想在屏幕方向改变时也调用oncreate方法意味着我想在方向改变时重新加载一个新的activity并保存媒体播放器状态请承认我当时卡住了我不知道什么错误。
SurfaceView videoSurface;
MediaPlayer player;
VideoControllerView controller;
private boolean mFullScreen = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
videoSurface = (SurfaceView) findViewById(R.id.videoSurface);
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
player = new MediaPlayer();
controller = new VideoControllerView(this);
try {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(this, Uri.parse("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"));
player.setOnPreparedListener(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
controller.show();
return false;
}
// Implement SurfaceHolder.Callback
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
player.setDisplay(holder);
player.prepareAsync();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
// End SurfaceHolder.Callback
// Implement MediaPlayer.OnPreparedListener
@Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(this);
controller.setAnchorView((FrameLayout) findViewById(R.id.videoSurfaceContainer));
player.start();
}
// End MediaPlayer.OnPreparedListener
// Implement VideoMediaController.MediaPlayerControl
@Override
public boolean canPause() {
return true;
}
@Override
public boolean canSeekBackward() {
return true;
}
@Override
public boolean canSeekForward() {
return true;
}
@Override
public int getBufferPercentage() {
return 0;
}
@Override
public int getCurrentPosition() {
return player.getCurrentPosition();
}
@Override
public int getDuration() {
return player.getDuration();
}
@Override
public boolean isPlaying() {
return player.isPlaying();
}
@Override
public void pause() {
player.pause();
}
@Override
public void seekTo(int i) {
player.seekTo(i);
}
@Override
public void start() {
player.start();
}
@Override
public boolean isFullScreen() {
if(mFullScreen){
Log.w("FullScreen", "--set icon full screen--");
Log.w("curr",player.getCurrentPosition()+"");
/* ImageButton mFullscreenButton=(ImageButton)controller.findViewById(R.id.fullscreen);
mFullscreenButton.setImageResource(R.drawable.ic_media_fullscreen_stretch);
*/ return false;
}else{
Log.w("FullScreen", "--set icon small full screen--");
return true;
}
}
@Override
public void toggleFullScreen() {
Log.w("FullScreen", "-----------------click toggleFullScreen-----------");
setFullScreen(isFullScreen());
}
// End VideoMediaController.MediaPlayerControl
public void setFullScreen(boolean fullScreen){
fullScreen = false;
if (mFullScreen)
{
Log.w("FullScreen", "-----------Set full screen SCREEN_ORIENTATION_LANDSCAPE------------");
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);
//set icon is full screen
mFullScreen = fullScreen;
}
else{
Log.w("FullScreen", "-----------Set small screen SCREEN_ORIENTATION_PORTRAIT------------");
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
final FrameLayout mFrame = (FrameLayout) findViewById(R.id.videoSurfaceContainer);
// int height = displaymetrics.heightPixels;
int height =225;//get height Frame Container video//mFrame.getHeight()
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);
//set icon is small screen
mFullScreen = !fullScreen;
}
}
@Override
protected void onSaveInstanceState(Bundle estadoguardado){
super.onSaveInstanceState(estadoguardado);
if(player!=null){
int pos=player.getCurrentPosition();
estadoguardado.putInt("posicion", pos);
}
}
@Override
protected void onRestoreInstanceState(Bundle estadoguardado)
{
super.onRestoreInstanceState(estadoguardado);
if(estadoguardado!=null && player!=null){
int pos=estadoguardado.getInt("posicion");
Log.w("position",pos+"");
player.seekTo(pos);
}
}
@Override
public void onResume()
{
super.onResume();
try {
//reinicia
Toast.makeText(this, "onResume2", Toast.LENGTH_SHORT).show();
if (player == null)
player.setDataSource(this, Uri.parse("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"));
player.seekTo(0);
player.setLooping(true);
player.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
@Override
public void onPause()
{
super.onPause();
Toast.makeText(this, "onPause2", Toast.LENGTH_SHORT).show();
//LIBERA A MEDIA PLAYER
if (player != null)
{
player.release();
player = null;
}
和其他 class 扩展自 frameLayout
当应用进入 运行
时有些崩溃
java.lang.IllegalStateException
at android.media.MediaPlayer.prepareAsync(Native Method)
at whizpool.videoplayerexample.VideoPlayerActivity.surfaceCreated(VideoPlayerActivity.java:70)
at android.view.SurfaceView.updateWindow(SurfaceView.java:554)
at android.view.SurfaceView.access[=12=]0(SurfaceView.java:81)
at android.view.SurfaceView.onPreDraw(SurfaceView.java:169)
at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:693)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1762)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4666)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511
10-12 10:00:48.726 2268-2268/whizpool.videoplayerexample E/MediaPlayer﹕ Attempt to perform seekTo in wrong state: mPlayer=0x18332b8, mCurrentState=2
10-12 10:00:48.726 2268-2268/whizpool.videoplayerexample E/MediaPlayer﹕ error (-38, 0)
10-12 10:00:48.727 2268-2268/whizpool.videoplayerexample E/MediaPlayer﹕ start called in state 0
10-12 10:00:48.727 2268-2268/whizpool.videoplayerexample E/MediaPlayer﹕ error (-38, 0)
10-12 10:00:48.738 2268-2268/whizpool.videoplayerexample E/MediaPlayer﹕ Error (-38,0)
10-12 10:00:48.738 2268-2268/whizpool.videoplayerexample E/MediaPlayer﹕ Error (-38,0)
10-12 10:00:48.885 2268-2268/whizpool.videoplayerexample E/MediaPlayer﹕ prepareAsync called in state 0
要在旋转时保存和恢复视频位置,您需要使用 onSaveInstanceState 和 onRestoreInstanceState。您可以使用此代码从 VideoView 保存视频位置。
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
VideoView videoView = (VideoView) findViewById(R.id.videoView);
videoPosition = videoView.getCurrentPosition();
if (videoView.canPause()) {
videoView.pause();
}
outState.putInt(VIDEO_POSITION_KEY, videoPosition);
Log.d(LOG_TAG, "onSaveInstanceState() Current Position Saved is: " + videoPosition);
}
...并使用此代码再次检索它。
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
videoPosition = savedInstanceState.getInt(VIDEO_POSITION_KEY, 0);
VideoView videoView = (VideoView) findViewById(R.id.videoView);
Log.d(LOG_TAG, "onRestoreInstanceState() - Seeking to position:" + Integer.toString(videoPosition));
videoView.seekTo(videoPosition); // this call should keep the video at the saved position
}
您需要在几秒钟后将方向重置为 SCREEN_ORIENTATION_SENSOR,以便传感器再次开始工作..
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
}, 2000);
我不熟悉使用表面视图在视频播放器中播放视频,现在我想保存媒体播放器的实例状态,当方向改变时,当视图重新加载或重新创建时,旧媒体播放器状态从旧位置开始,而不是加载到原始位置意味着在零位置我在清单中设置屏幕方向但那个时候oncreate没有被调用我想在屏幕方向改变时也调用oncreate方法意味着我想在方向改变时重新加载一个新的activity并保存媒体播放器状态请承认我当时卡住了我不知道什么错误。
SurfaceView videoSurface;
MediaPlayer player;
VideoControllerView controller;
private boolean mFullScreen = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
videoSurface = (SurfaceView) findViewById(R.id.videoSurface);
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
player = new MediaPlayer();
controller = new VideoControllerView(this);
try {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(this, Uri.parse("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"));
player.setOnPreparedListener(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
controller.show();
return false;
}
// Implement SurfaceHolder.Callback
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
player.setDisplay(holder);
player.prepareAsync();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
// End SurfaceHolder.Callback
// Implement MediaPlayer.OnPreparedListener
@Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(this);
controller.setAnchorView((FrameLayout) findViewById(R.id.videoSurfaceContainer));
player.start();
}
// End MediaPlayer.OnPreparedListener
// Implement VideoMediaController.MediaPlayerControl
@Override
public boolean canPause() {
return true;
}
@Override
public boolean canSeekBackward() {
return true;
}
@Override
public boolean canSeekForward() {
return true;
}
@Override
public int getBufferPercentage() {
return 0;
}
@Override
public int getCurrentPosition() {
return player.getCurrentPosition();
}
@Override
public int getDuration() {
return player.getDuration();
}
@Override
public boolean isPlaying() {
return player.isPlaying();
}
@Override
public void pause() {
player.pause();
}
@Override
public void seekTo(int i) {
player.seekTo(i);
}
@Override
public void start() {
player.start();
}
@Override
public boolean isFullScreen() {
if(mFullScreen){
Log.w("FullScreen", "--set icon full screen--");
Log.w("curr",player.getCurrentPosition()+"");
/* ImageButton mFullscreenButton=(ImageButton)controller.findViewById(R.id.fullscreen);
mFullscreenButton.setImageResource(R.drawable.ic_media_fullscreen_stretch);
*/ return false;
}else{
Log.w("FullScreen", "--set icon small full screen--");
return true;
}
}
@Override
public void toggleFullScreen() {
Log.w("FullScreen", "-----------------click toggleFullScreen-----------");
setFullScreen(isFullScreen());
}
// End VideoMediaController.MediaPlayerControl
public void setFullScreen(boolean fullScreen){
fullScreen = false;
if (mFullScreen)
{
Log.w("FullScreen", "-----------Set full screen SCREEN_ORIENTATION_LANDSCAPE------------");
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);
//set icon is full screen
mFullScreen = fullScreen;
}
else{
Log.w("FullScreen", "-----------Set small screen SCREEN_ORIENTATION_PORTRAIT------------");
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
final FrameLayout mFrame = (FrameLayout) findViewById(R.id.videoSurfaceContainer);
// int height = displaymetrics.heightPixels;
int height =225;//get height Frame Container video//mFrame.getHeight()
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);
//set icon is small screen
mFullScreen = !fullScreen;
}
}
@Override
protected void onSaveInstanceState(Bundle estadoguardado){
super.onSaveInstanceState(estadoguardado);
if(player!=null){
int pos=player.getCurrentPosition();
estadoguardado.putInt("posicion", pos);
}
}
@Override
protected void onRestoreInstanceState(Bundle estadoguardado)
{
super.onRestoreInstanceState(estadoguardado);
if(estadoguardado!=null && player!=null){
int pos=estadoguardado.getInt("posicion");
Log.w("position",pos+"");
player.seekTo(pos);
}
}
@Override
public void onResume()
{
super.onResume();
try {
//reinicia
Toast.makeText(this, "onResume2", Toast.LENGTH_SHORT).show();
if (player == null)
player.setDataSource(this, Uri.parse("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"));
player.seekTo(0);
player.setLooping(true);
player.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
@Override
public void onPause()
{
super.onPause();
Toast.makeText(this, "onPause2", Toast.LENGTH_SHORT).show();
//LIBERA A MEDIA PLAYER
if (player != null)
{
player.release();
player = null;
}
和其他 class 扩展自 frameLayout
当应用进入 运行
时有些崩溃java.lang.IllegalStateException
at android.media.MediaPlayer.prepareAsync(Native Method)
at whizpool.videoplayerexample.VideoPlayerActivity.surfaceCreated(VideoPlayerActivity.java:70)
at android.view.SurfaceView.updateWindow(SurfaceView.java:554)
at android.view.SurfaceView.access[=12=]0(SurfaceView.java:81)
at android.view.SurfaceView.onPreDraw(SurfaceView.java:169)
at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:693)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1762)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4666)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511
10-12 10:00:48.726 2268-2268/whizpool.videoplayerexample E/MediaPlayer﹕ Attempt to perform seekTo in wrong state: mPlayer=0x18332b8, mCurrentState=2
10-12 10:00:48.726 2268-2268/whizpool.videoplayerexample E/MediaPlayer﹕ error (-38, 0)
10-12 10:00:48.727 2268-2268/whizpool.videoplayerexample E/MediaPlayer﹕ start called in state 0
10-12 10:00:48.727 2268-2268/whizpool.videoplayerexample E/MediaPlayer﹕ error (-38, 0)
10-12 10:00:48.738 2268-2268/whizpool.videoplayerexample E/MediaPlayer﹕ Error (-38,0)
10-12 10:00:48.738 2268-2268/whizpool.videoplayerexample E/MediaPlayer﹕ Error (-38,0)
10-12 10:00:48.885 2268-2268/whizpool.videoplayerexample E/MediaPlayer﹕ prepareAsync called in state 0
要在旋转时保存和恢复视频位置,您需要使用 onSaveInstanceState 和 onRestoreInstanceState。您可以使用此代码从 VideoView 保存视频位置。
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
VideoView videoView = (VideoView) findViewById(R.id.videoView);
videoPosition = videoView.getCurrentPosition();
if (videoView.canPause()) {
videoView.pause();
}
outState.putInt(VIDEO_POSITION_KEY, videoPosition);
Log.d(LOG_TAG, "onSaveInstanceState() Current Position Saved is: " + videoPosition);
}
...并使用此代码再次检索它。
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
videoPosition = savedInstanceState.getInt(VIDEO_POSITION_KEY, 0);
VideoView videoView = (VideoView) findViewById(R.id.videoView);
Log.d(LOG_TAG, "onRestoreInstanceState() - Seeking to position:" + Integer.toString(videoPosition));
videoView.seekTo(videoPosition); // this call should keep the video at the saved position
}
您需要在几秒钟后将方向重置为 SCREEN_ORIENTATION_SENSOR,以便传感器再次开始工作..
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
new Handler().postDelayed(new Runnable() {
@Override public void run() { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } }, 2000);