在调用android api播放视频,使用MediaPlayer一文中讲述了利用MediaPlayer播放文件,但是android在横竖屏变换时,其生命周期发生了变换,见:android屏幕切换与生命周期。

要想实现在变换横竖屏时,继续播放之前的文件,就要记录播放文件的时间,在下次播放的时候,从此处开始播放即可。正好MediaPlayer提供这两个方法,利用getCurrentPosition()得到当前播放的毫秒数,利用seekTo(i)播放文件从i毫秒开始播放。从而实现了继续播放文件。

其代码:

package com.easymorse;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
public class androidmp4demo extends Activity {
    private String path = "http://dev.mopietek.net:8080/mp4/avi512.mp4";
    private  VideoView mVideoView;
    private static int i = 0;
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.videoview);
        mVideoView = (VideoView) findViewById(R.id.surface_view);
        if (path == "") {
            Toast.makeText(
                    androidmp4demo.this,
                    "Please edit VideoViewDemo Activity, and set path"
                            + " variable to your media file URL/path",
                    Toast.LENGTH_LONG).show();
        } else {
            mVideoView.setVideoPath(path);
            MediaController controller = new MediaController(this);
            mVideoView.setMediaController(controller);
            mVideoView.requestFocus();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i("mp4", "@@@ on start");
    }

    @Override
    protected void onResume() {
        super.onResume();
        mVideoView.seekTo(i);
        mVideoView.start();
        Log.i("mp4", "@@@ on resume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i("mp4", "@@@ on pause");
    }
    @Override
    protected void onStop() {
        super.onStop();
            mVideoView.pause();
            i = mVideoView.getCurrentPosition();
        Log.i("mp4", "@@@ on stop");
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mVideoView.destroyDrawingCache();
        Log.i("mp4", "@@@ on destroy");
    }
}

源代码见:https://easymorse.googlecode.com/svn/trunk/Mp4Demo