我有一个显示不同视频文件的活动。当我单击视频文件时,我会进入另一个 Activity,其中 VideoView 会播放视频。
我的问题是,当我想退出此活动并返回到上一个活动时,我应该单击两次后退按钮才能返回。如果我只单击一次,视频会再次开始播放,并且只有在第二次尝试时我才可以退出屏幕。
然后我尝试了这个:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Log.d(Constants.LOG_TAG, "back pressed in videoplayer");
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
而且,尽管我在 logcat 中看到“在视频播放器中按下回键”,但该活动不会退出。我还是应该按两次后退按钮。
EDIT:这是最相关的(我认为)源代码。但请注意,视频是从互联网播放的,我没有使用媒体控制器,而是定义自己的布局并链接到视频视图控件。
public class VideoPlayer extends Activity implements OnClickListener, OnCompletionListener,
OnSeekBarChangeListener, OnPreparedListener, OnTouchListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video_view);
// Gets the position of clicked video, from an ArrayList of video urls.
selectedVideo = getPosition();
// the play button
play = (ImageButton) findViewById(R.id.play);
play.setOnClickListener(this);
videoView = (VideoView) findViewById(R.id.videoView);
videoView.setOnCompletionListener(this);
videoView.setOnPreparedListener(this);
videoView.setOnTouchListener(this);
// the url to play
String path = videoUris.get(selectedVideo);
videoView.setVideoPath(getPath(path));
}
/**
* Play or Pause the current video file.
*
* If the video is paused, then invoking this method should start it. If the video is already playing, then the
* video should pause.
*/
private void play() {
if (!isVideoStarted) {
isVideoStarted = true;
videoView.start();
play.setImageResource(R.drawable.video_pause);
videoSeekBar.post(updateSeekBarRunnable);
} else if (isVideoStarted) {
isVideoStarted = false;
pause();
}
}
/**
* Start playing back a video file with the specified Uri.
*/
private void startPlayback() {
String path = videoUris.get(selectedVideo);
videoView.setVideoPath(getPath(path));
videoView.start();
}
/**
* Stops the currently playing video. (The SeekBar position is reset to beginning, 0.)
*/
private void stopPlayback() {
videoView.stopPlayback();
}
/**
* Pause the currently playing video. (The SeekBar remains in its position.)
*/
private void pause() {
videoView.pause();
@Override
public void onPrepared(MediaPlayer mp) {
play();
}
}