如何在按下主页按钮并重新打开应用程序后在Android中恢复MediaPlayer

时间:2014-05-17 20:57:14

标签: android android-mediaplayer surfaceview onresume

我尝试了很多方法,我对我的代码进行了很多更改,我阅读了Android MediaPlayer文档,我尝试了StackOverflow示例,但没有一个可以解决我的问题。

我的问题:当我按下模拟器或手机的主页按钮然后重新打开应用程序时,它从头开始。

希望你能帮助我。提前谢谢。

这是我的代码:

public class Mediaplayer extends Activity implements OnCompletionListener,
    OnErrorListener, OnInfoListener, OnPreparedListener,
    OnSeekCompleteListener, OnVideoSizeChangedListener,
    SurfaceHolder.Callback, MediaController.MediaPlayerControl {
Display currentDisplay;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
MediaPlayer mediaPlayer;
MediaController controller;
int videoWidth = 0;
int videoHeight = 0;
boolean readyToPlay = false;
public final static String LOGTAG = "CUSTOM_VIDEO_PLAYER";

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.video);

    surfaceView = (SurfaceView) this.findViewById(R.id.SurfaceView);
    surfaceHolder = surfaceView.getHolder();
    surfaceHolder.addCallback(this);
    surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setOnInfoListener(this);
    mediaPlayer.setOnPreparedListener(this);
    mediaPlayer.setOnSeekCompleteListener(this);
    mediaPlayer.setOnVideoSizeChangedListener(this);
    mediaPlayer.setWakeMode(getApplicationContext(),
            PowerManager.PARTIAL_WAKE_LOCK);
    String filePath = "http://cdn.example.com/wp-content/uploads/Almost.Human-S01E10.mp4";

    try {
        mediaPlayer.setDataSource(filePath);
    } catch (IllegalArgumentException e) {
        Log.v(LOGTAG, e.getMessage());
        finish();
    } catch (IllegalStateException e) {
        Log.v(LOGTAG, e.getMessage());
        finish();
    } catch (IOException e) {
        Log.v(LOGTAG, e.getMessage());
        finish();
    }

    controller = new MediaController(this);
    currentDisplay = getWindowManager().getDefaultDisplay();

}

public void surfaceCreated(SurfaceHolder holder) {
    // Log.v(LOGTAG, "surfaceCreated Called");

    mediaPlayer.setDisplay(holder);

    try {
        mediaPlayer.prepare();
    } catch (IllegalStateException e) {
        // Log.v(LOGTAG, e.getMessage());
        finish();
    } catch (IOException e) {
        // Log.v(LOGTAG, e.getMessage());
        finish();
    }
}

public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {
    Log.v(LOGTAG, "surfaceChanged Called");
}

public void surfaceDestroyed(SurfaceHolder holder) {
    Log.v(LOGTAG, "surfaceDestroyed Called");
}

public void onCompletion(MediaPlayer mp) {
    Log.v(LOGTAG, "onCompletion Called");
    finish();
}

public boolean onError(MediaPlayer mp, int whatError, int extra) {
    Log.v(LOGTAG, "onError Called");

    if (whatError == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
        Log.v(LOGTAG, "Media Error, Server Died " + extra);
    } else if (whatError == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
        Log.v(LOGTAG, "Media Error, Error Unknown " + extra);
    }

    return false;
}

public boolean onInfo(MediaPlayer mp, int whatInfo, int extra) {
    if (whatInfo == MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING) {
        Log.v(LOGTAG, "Media Info, Media Info Bad Interleaving " + extra);
    } else if (whatInfo == MediaPlayer.MEDIA_INFO_NOT_SEEKABLE) {
        Log.v(LOGTAG, "Media Info, Media Info Not Seekable " + extra);
    } else if (whatInfo == MediaPlayer.MEDIA_INFO_UNKNOWN) {
        Log.v(LOGTAG, "Media Info, Media Info Unknown " + extra);
    } else if (whatInfo == MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING) {
        Log.v(LOGTAG, "MediaInfo, Media Info Video Track Lagging " + extra);
        /*
         * Android Version 2.0 and Higher } else if (whatInfo ==
         * MediaPlayer.MEDIA_INFO_METADATA_UPDATE) {
         * Log.v(LOGTAG,"MediaInfo, Media Info Metadata Update " + extra);
         */
    }
    return false;
}

public void onPrepared(MediaPlayer mp) {
    Log.v(LOGTAG, "onPrepared Called");
    videoWidth = mp.getVideoWidth();
    videoHeight = mp.getVideoHeight();

    if (videoWidth > currentDisplay.getWidth()
            || videoHeight > currentDisplay.getHeight()) {
        float heightRatio = (float) videoHeight
                / (float) currentDisplay.getHeight();
        float widthRatio = (float) videoWidth
                / (float) currentDisplay.getWidth();

        if (heightRatio > 1 || widthRatio > 1) {
            if (heightRatio > widthRatio) {
                videoHeight = (int) Math.ceil((float) videoHeight
                        / (float) heightRatio);
                videoWidth = (int) Math.ceil((float) videoWidth
                        / (float) heightRatio);
            } else {
                videoHeight = (int) Math.ceil((float) videoHeight
                        / (float) widthRatio);
                videoWidth = (int) Math.ceil((float) videoWidth
                        / (float) widthRatio);
            }
        }
    }

    surfaceView.setLayoutParams(new LinearLayout.LayoutParams(videoWidth,
            videoHeight));
    mp.start();

    controller.setMediaPlayer(this);
    controller.setAnchorView(this.findViewById(R.id.MainView));
    controller.setEnabled(true);
    controller.show();
}

@Override
protected void onPause() {
    super.onPause();
    if (mediaPlayer.isPlaying()) {
        mediaPlayer.pause();
    } else {
        return;
    }
}

public void onSeekComplete(MediaPlayer mp) {
    Log.v(LOGTAG, "onSeekComplete Called");
}

public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
    Log.v(LOGTAG, "onVideoSizeChanged Called");
}

public boolean canPause() {
    return true;
}

public boolean canSeekBackward() {
    return true;
}

public boolean canSeekForward() {
    return true;
}

public int getBufferPercentage() {
    return 0;
}

public int getCurrentPosition() {
    return mediaPlayer.getCurrentPosition();
}

public int getDuration() {
    return mediaPlayer.getDuration();
}

public boolean isPlaying() {
    return mediaPlayer.isPlaying();
}

public void pause() {

    mediaPlayer.pause();

}

public void seekTo(int pos) {
    mediaPlayer.seekTo(pos);
}

public void start() {
    mediaPlayer.start();
}

@Override
public boolean onTouchEvent(MotionEvent ev) {

    controller.show();

    return false;
}

@Override
public int getAudioSessionId() {
    // TODO Auto-generated method stub
    return 0;
}

 }

2 个答案:

答案 0 :(得分:16)

我知道您已经接受了答案,但我会根据您对您的问题的评论以及您和Nana对Nana答案的评论来解释问题所在。

  1. SurfaceView不再可见时会被销毁,并在再次可见时重新创建。
  2. 您正在使用mp.pause() Activity方法拨打onPause()
  3. 当你去最近的'应用列表并尝试重新启动应用,重新创建SurfaceView
  4. surfaceCreated方法中,您呼叫mp.prepare(),但此时mp处于暂停状态,并且在暂停的prepare()上呼叫Mediaplayer会抛弃IllegalStateException
  5. 您有一个try / catch阻止IllegalStateException并且呼叫finish() - 这就是为什么第一次尝试从最近的'重新启动应用。 list导致Activity被销毁。
  6. 由于上述一系列事件,您需要再次尝试从最近的'重新打开应用程序。列表,但是当Activity被销毁时,它将经历完整创建(调用onCreate(..)。这就是它从一开始就开始的原因。
  7. Nana的答案是一种解决方法,但它仍然意味着必须使用两次尝试重新启动Activity来自最近的'列表。

    不幸的是,MediaPlayer类缺乏检查“状态”的方法。 isPlaying是任何州唯一有用的方法。遗憾的是,开发人员没有考虑添加getState()方法(或类似方法)来检查它是否已启动,播放,停止,暂停等等。

    阻止IllegalStateException的一种方法是使用名为isPaused的布尔值(例如),然后修改Activity onPause(),如下所示......

    if (mediaPlayer.isPlaying()) {
        mediaPlayer.pause();
        isPaused = true;
    }
    

    ...并在surfaceCreated(...) ...

    try {
        if (isPaused) {
            mpStart();
            isPaused = false;
        }
        else
            mediaPlayer.prepare();
    }
    // catch blocks here
    

答案 1 :(得分:1)

正在重新启动活动,从而触发surfaceCreated()和mediaPlayer.prepare(),它们依次调用onPrepared和mp.start()来重启轨道。你没有恢复播放的机制。这样做 - 暂停时获取曲目的最后位置(按下HOME按钮),然后当活动被重新创建时#34;通过寻找最后一个位置来恢复播放曲目。修改你的onPause()和onPrepared(),如下所示:

int length = 0;


//save last position when activity is paused

@Override
protected void onPause() {
    super.onPause();
    if (mediaPlayer.isPlaying()) {
        mediaPlayer.pause();
   length = mediaPlayer.getCurrentPosition();

    } else {
        return;
    }
}


public void onPrepared(MediaPlayer mp) {
........
.........
.........
 mp.start();
//seek to saved position. 
 mp.seekTo(length);

}