发生这种情况的原因是 MediaPlayer 正在调用您传递给它的 SurfaceHolder 的 setKeepScreenOn 方法。您可以通过创建自定义 SurfaceHolder 实现 Class 并覆盖 setKeepScreenOn 来解决此问题,如下所示:
package com.justinbuser.videolivewallpapers;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.Surface;
import android.view.SurfaceHolder;
public class VideoSurfaceHolder implements SurfaceHolder {
private SurfaceHolder surfaceHolder;
public VideoSurfaceHolder(SurfaceHolder holder) {
surfaceHolder = holder;
}
@Override
public void addCallback(Callback callback) {
surfaceHolder.addCallback(callback);
}
@Override
public Surface getSurface() {
return surfaceHolder.getSurface();
}
@Override
public Rect getSurfaceFrame() {
return surfaceHolder.getSurfaceFrame();
}
@Override
public boolean isCreating() {
return surfaceHolder.isCreating();
}
@Override
public Canvas lockCanvas() {
return surfaceHolder.lockCanvas();
}
@Override
public Canvas lockCanvas(Rect dirty) {
return surfaceHolder.lockCanvas(dirty);
}
@Override
public void removeCallback(Callback callback) {
surfaceHolder.removeCallback(callback);
}
@Override
public void setFixedSize(int width, int height) {
surfaceHolder.getSurface().setSize(width, height);
surfaceHolder.setSizeFromLayout();
}
@Override
public void setFormat(int format) {
surfaceHolder.setFormat(format);
}
@Override
public void setSizeFromLayout() {
surfaceHolder.setSizeFromLayout();
}
@Override
public void setType(int type) {
surfaceHolder.setType(SURFACE_TYPE_PUSH_BUFFERS);
}
@Override
public void setKeepScreenOn(boolean bool){
//do nothing
}
@Override
public void unlockCanvasAndPost(Canvas canvas) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
然后,当您只需要对上面发布的代码进行细微更改时,即:
mp.setDisplay(new VideoSurfaceHolder(holder));
您接下来将遇到的问题是您的视频会播放,但您只会听到音频。经过几个小时的头发拉扯等……您会意识到无论出于何种原因 setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS) 都无法正常工作。如果你在 onCreate 中调用它,那么它可以工作,但 surfaceCreated 等......永远不会被调用,如果你在 onSurfaceCreated 中调用它,那么为时已晚。我自己还没有解决这个问题,但我会及时通知你。