Activity里的onSaveInstanceState()方法,虽然系统会自动调用它来保存Activity的一些数据,但当除它默认要保存的数据外,我们还要保存一些其他数据的时候, 我们就需要覆盖onSaveInstanceState()方法来保存Activity的附件信息。例如在播放视频过程中,横竖屏切换要保持当前播放时间进度,在默认情况下播放时间是不被自动保存的。
写了一个简单的播放视频的例子,在横竖屏切换时保持当前播放进度,效果图:
横屏切换:
mian.xml的代码:
[html] view plaincopy
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical" android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <VideoView android:id="@+id/myvideo" android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </LinearLayout>
MainAcrtivity主要代码部分:
[java] view plaincopy
- private VideoView videoView;
- private static final String VIDEO_PATH = Environment
- .getExternalStorageDirectory()
- + File.separator
- + "mymovie"
- + File.separator + "shenghuaweiji.mp4";
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Log.v("tag", "onCreate");
- if (videoView == null) {
- videoView = (VideoView) this.findViewById(R.id.myvideo);
- MediaController controller = new MediaController(this);
- videoView.setMediaController(controller);
- videoView.setVideoPath(VIDEO_PATH);
- videoView.requestFocus();
- }
- if (savedInstanceState != null
- && savedInstanceState.getInt("currentposition") != 0) {
- videoView.seekTo(savedInstanceState.getInt("currentposition"));
- }
- videoView.start();
- }
onCreate方法中的参数savedInstanceState就是保存的Activity一些状态。
[java] view plaincopy
- savedInstanceState.getInt("currentposition")
获取视频播放时间。
实现并覆盖了onSaveInstanceState方法:
[java] view plaincopy
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- // TODO Auto-generated method stub
- outState.putInt("currentposition", videoView.getCurrentPosition());
- Log.v("tag", "onSaveInstanceState");
- super.onSaveInstanceState(outState);
- }
红色代码是将当前video的播放时间存储在Bundle中。
这样在横竖屏切换时保证了播放状态,源代码:http://bigcateasymorse.googlecode.com/svn/trunk/save-activity-state1.0/
时间: 2024-11-07 06:11:32