下面列出了android.view.Surface#release ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void playVideo() {
try {
mCameraSupport.release();
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(mVideoFilePath);
Surface surface = new Surface(mTextureView.getSurfaceTexture());
mMediaPlayer.setSurface(surface);
surface.release();
mMediaPlayer.setLooping(true);
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void drawSizeMismatchSnapshot(GraphicBuffer buffer) {
final SurfaceSession session = new SurfaceSession(mSurface);
// Keep a reference to it such that it doesn't get destroyed when finalized.
mChildSurfaceControl = new SurfaceControl.Builder(session)
.setName(mTitle + " - task-snapshot-surface")
.setSize(buffer.getWidth(), buffer.getHeight())
.setFormat(buffer.getFormat())
.build();
Surface surface = new Surface();
surface.copyFrom(mChildSurfaceControl);
// Clip off ugly navigation bar.
final Rect crop = calculateSnapshotCrop();
final Rect frame = calculateSnapshotFrame(crop);
SurfaceControl.openTransaction();
try {
// We can just show the surface here as it will still be hidden as the parent is
// still hidden.
mChildSurfaceControl.show();
mChildSurfaceControl.setWindowCrop(crop);
mChildSurfaceControl.setPosition(frame.left, frame.top);
// Scale the mismatch dimensions to fill the task bounds
final float scale = 1 / mSnapshot.getScale();
mChildSurfaceControl.setMatrix(scale, 0, 0, scale);
} finally {
SurfaceControl.closeTransaction();
}
surface.attachAndQueueBuffer(buffer);
surface.release();
final Canvas c = mSurface.lockCanvas(null);
drawBackgroundAndBars(c, frame);
mSurface.unlockCanvasAndPost(c);
mSurface.release();
}
AppWindowThumbnail(Transaction t, AppWindowToken appToken, GraphicBuffer thumbnailHeader) {
mAppToken = appToken;
mSurfaceAnimator = new SurfaceAnimator(this, this::onAnimationFinished, appToken.mService);
mWidth = thumbnailHeader.getWidth();
mHeight = thumbnailHeader.getHeight();
// Create a new surface for the thumbnail
WindowState window = appToken.findMainWindow();
// TODO: This should be attached as a child to the app token, once the thumbnail animations
// use relative coordinates. Once we start animating task we can also consider attaching
// this to the task.
mSurfaceControl = appToken.makeSurface()
.setName("thumbnail anim: " + appToken.toString())
.setSize(mWidth, mHeight)
.setFormat(PixelFormat.TRANSLUCENT)
.setMetadata(appToken.windowType,
window != null ? window.mOwnerUid : Binder.getCallingUid())
.build();
if (SHOW_TRANSACTIONS) {
Slog.i(TAG, " THUMBNAIL " + mSurfaceControl + ": CREATE");
}
// Transfer the thumbnail to the surface
Surface drawSurface = new Surface();
drawSurface.copyFrom(mSurfaceControl);
drawSurface.attachAndQueueBuffer(thumbnailHeader);
drawSurface.release();
t.show(mSurfaceControl);
// We parent the thumbnail to the task, and just place it on top of anything else in the
// task.
t.setLayer(mSurfaceControl, Integer.MAX_VALUE);
}
@Override
public void setSurface(IBinder sessionToken, Surface surface, int userId) {
final int callingUid = Binder.getCallingUid();
final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
userId, "setSurface");
final long identity = Binder.clearCallingIdentity();
try {
synchronized (mLock) {
try {
SessionState sessionState = getSessionStateLocked(sessionToken, callingUid,
resolvedUserId);
if (sessionState.hardwareSessionToken == null) {
getSessionLocked(sessionState).setSurface(surface);
} else {
getSessionLocked(sessionState.hardwareSessionToken,
Process.SYSTEM_UID, resolvedUserId).setSurface(surface);
}
} catch (RemoteException | SessionNotFoundException e) {
Slog.e(TAG, "error in setSurface", e);
}
}
} finally {
if (surface != null) {
// surface is not used in TvInputManagerService.
surface.release();
}
Binder.restoreCallingIdentity(identity);
}
}
@Override
protected Object doInBackground(Object[] objects) {
LogUtil.d("ReleasePlayerTask doInBackground");
AudioManager audioManager = audioManagerWeakReference.get();
if (audioManager != null) {
audioManager.abandonAudioFocus(null);
audioManagerWeakReference.clear();
audioManagerWeakReference = null;
LogUtil.d("ReleasePlayerTask release audioManager");
}
IMediaPlayer iMediaPlayer = mediaPlayerWeakReference.get();
if (iMediaPlayer != null) {
iMediaPlayer.release();
mediaPlayerWeakReference.clear();
mediaPlayerWeakReference = null;
LogUtil.d("ReleasePlayerTask release iMediaPlayer");
}
SurfaceTexture surfaceTexture = surfaceTextureWeakReference.get();
if (surfaceTexture != null) {
surfaceTexture.release();
surfaceTextureWeakReference.clear();
surfaceTextureWeakReference = null;
LogUtil.d("ReleasePlayerTask release surfaceTexture");
}
Surface surface = surfaceWeakReference.get();
if (surface != null) {
surface.release();
surfaceWeakReference.clear();
surfaceWeakReference = null;
LogUtil.d("ReleasePlayerTask release surface");
}
return null;
}
public void setMediaPlayer(MediaPlayer player) {
mMediaPlayer = player;
if (mSurfaceTexture != null) {
Surface surface = new Surface(mSurfaceTexture);
mMediaPlayer.setSurface(surface);
surface.release();
try {
mMediaPlayer.prepare();
} catch (IOException t) {
Log.e(TAG, "media player prepare failed");
}
}
}
private void setSurface(int mTextureID){
mSurfaceTexture = new SurfaceTexture(mTextureID);
mSurfaceTexture.setOnFrameAvailableListener(this);
Surface surface = new Surface(mSurfaceTexture);
mMediaPlayer.setSurface(surface);
surface.release();
}
public void setSurface(int mTextureID){
mSurfaceTexture = new SurfaceTexture(mTextureID);
mSurfaceTexture.setOnFrameAvailableListener(this);
Surface surface = new Surface(mSurfaceTexture);
mMediaPlayer.setSurface(surface);
surface.release();
}
@Override
public void onSurfaceCreated(GL10 glUnused, EGLConfig config) {
super.init();
/*
* Create the SurfaceTexture that will feed this textureID, and pass
* it to the MediaPlayer
*/
mSurface = new SurfaceTexture(getTexture());
mSurface.setOnFrameAvailableListener(this);
Surface surface = new Surface(mSurface);
mMediaPlayer.setSurface(surface);
mMediaPlayer.setScreenOnWhilePlaying(true);
surface.release();
if (!isMediaPlayerPrepared) {
try {
mMediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
isMediaPlayerPrepared = true;
}
synchronized (this) {
updateSurface = false;
}
mMediaPlayer.start();
}
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
final Surface surface = new Surface(surfaceTexture);
final Canvas canvas = surface.lockCanvas(null);
mDrawer.onDrawPlaceholder(canvas);
surface.unlockCanvasAndPost(canvas);
surface.release();
}
private boolean captureScreenshotTextureAndSetViewport() {
if (!attachEglContext()) {
return false;
}
try {
if (!mTexNamesGenerated) {
GLES20.glGenTextures(1, mTexNames, 0);
if (checkGlErrors("glGenTextures")) {
return false;
}
mTexNamesGenerated = true;
}
final SurfaceTexture st = new SurfaceTexture(mTexNames[0]);
final Surface s = new Surface(st);
try {
SurfaceControl.screenshot(SurfaceControl.getBuiltInDisplay(
SurfaceControl.BUILT_IN_DISPLAY_ID_MAIN), s);
st.updateTexImage();
st.getTransformMatrix(mTexMatrix);
} finally {
s.release();
st.release();
}
// Set up texture coordinates for a quad.
// We might need to change this if the texture ends up being
// a different size from the display for some reason.
mTexCoordBuffer.put(0, 0f); mTexCoordBuffer.put(1, 0f);
mTexCoordBuffer.put(2, 0f); mTexCoordBuffer.put(3, 1f);
mTexCoordBuffer.put(4, 1f); mTexCoordBuffer.put(5, 1f);
mTexCoordBuffer.put(6, 1f); mTexCoordBuffer.put(7, 0f);
// Set up our viewport.
GLES20.glViewport(0, 0, mDisplayWidth, mDisplayHeight);
ortho(0, mDisplayWidth, 0, mDisplayHeight, -1, 1);
} finally {
detachEglContext();
}
return true;
}
public void onSurfaceCreated(GL10 glUnused, EGLConfig config) {
mProgram = createProgram(mVertexShader, mFragmentShader);
if (mProgram == 0) {
return;
}
maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
checkGlError("glGetAttribLocation aPosition");
if (maPositionHandle == -1) {
throw new RuntimeException("Could not get attrib location for aPosition");
}
maTextureHandle = GLES20.glGetAttribLocation(mProgram, "aTextureCoord");
checkGlError("glGetAttribLocation aTextureCoord");
if (maTextureHandle == -1) {
throw new RuntimeException("Could not get attrib location for aTextureCoord");
}
muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
checkGlError("glGetUniformLocation uMVPMatrix");
if (muMVPMatrixHandle == -1) {
throw new RuntimeException("Could not get attrib location for uMVPMatrix");
}
muSTMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uSTMatrix");
checkGlError("glGetUniformLocation uSTMatrix");
if (muSTMatrixHandle == -1) {
throw new RuntimeException("Could not get attrib location for uSTMatrix");
}
int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
mTextureID = textures[0];
GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureID);
checkGlError("glBindTexture mTextureID");
GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER,
GLES20.GL_LINEAR);
GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER,
GLES20.GL_LINEAR);
/*
* Create the SurfaceTexture that will feed this textureID,
* and pass it to the MediaPlayer
*/
mSurfaceTexture = new SurfaceTexture(mTextureID);
mSurfaceTexture.setOnFrameAvailableListener(this);
if (mMediaPlayer != null) {
Surface surface = new Surface(mSurfaceTexture);
mMediaPlayer.setSurface(surface);
surface.release();
try {
mMediaPlayer.prepare();
} catch (IOException t) {
Log.e(TAG, "media player prepare failed");
}
}
synchronized(this) {
mUpdateSurface = false;
}
}
/**
* onClick handler for "play"/"stop" button.
*/
public void clickPlayStop(@SuppressWarnings("unused") View unused) {
if (mShowStopLabel) {
Log.d(TAG, "stopping movie");
stopPlayback();
// Don't update the controls here -- let the task thread do it after the movie has
// actually stopped.
//mShowStopLabel = false;
//updateControls();
} else {
if (mPlayTask != null) {
Log.w(TAG, "movie already playing");
return;
}
Log.d(TAG, "starting movie");
SpeedControlCallback callback = new SpeedControlCallback();
if (((CheckBox) findViewById(R.id.locked60fps_checkbox)).isChecked()) {
// TODO: consider changing this to be "free running" mode
callback.setFixedPlaybackRate(60);
}
SurfaceTexture st = mTextureView.getSurfaceTexture();
Surface surface = new Surface(st);
MoviePlayer player = null;
try {
player = new MoviePlayer(
new File(Environment.getExternalStorageDirectory(), mMovieFiles[mSelectedMovie]), surface, callback);
} catch (IOException ioe) {
Log.e(TAG, "Unable to play movie", ioe);
surface.release();
return;
}
adjustAspectRatio(player.getVideoWidth(), player.getVideoHeight());
mPlayTask = new MoviePlayer.PlayTask(player, this);
if (((CheckBox) findViewById(R.id.loopPlayback_checkbox)).isChecked()) {
mPlayTask.setLoopMode(true);
}
mShowStopLabel = true;
updateControls();
mPlayTask.execute();
}
}
/**
* onClick handler for "play"/"stop" button.
*/
public void clickPlayStop(@SuppressWarnings("unused") View unused) {
if (mShowStopLabel) {
Log.d(TAG, "stopping movie");
stopPlayback();
// Don't update the controls here -- let the task thread do it after the movie has
// actually stopped.
//mShowStopLabel = false;
//updateControls();
} else {
if (mPlayTask != null) {
Log.w(TAG, "movie already playing");
return;
}
Log.d(TAG, "starting movie");
SpeedControlCallback callback = new SpeedControlCallback();
SurfaceHolder holder = mSurfaceView.getHolder();
Surface surface = holder.getSurface();
// Don't leave the last frame of the previous video hanging on the screen.
// Looks weird if the aspect ratio changes.
clearSurface(surface);
MoviePlayer player = null;
try {
player = new MoviePlayer(
new File(Environment.getExternalStorageDirectory(), mMovieFiles[mSelectedMovie]), surface, callback);
} catch (IOException ioe) {
Log.e(TAG, "Unable to play movie", ioe);
surface.release();
return;
}
AspectFrameLayout layout = (AspectFrameLayout) findViewById(R.id.playMovie_afl);
int width = player.getVideoWidth();
int height = player.getVideoHeight();
layout.setAspectRatio((double) width / height);
//holder.setFixedSize(width, height);
mPlayTask = new MoviePlayer.PlayTask(player, this);
mShowStopLabel = true;
updateControls();
mPlayTask.execute();
}
}
@Override
public void run() {
try {
mGifInfoHandle = mInputSource.open();
} catch (IOException ex) {
mIOException = ex;
return;
}
GifTextureView.super.setSurfaceTextureListener(this);
final boolean isSurfaceAvailable = isAvailable();
isSurfaceValid.set(isSurfaceAvailable);
if (isSurfaceAvailable) {
post(new Runnable() {
@Override
public void run() {
updateTextureViewSize(mGifInfoHandle);
}
});
}
mGifInfoHandle.setSpeedFactor(mSpeedFactor);
while (!isInterrupted()) {
try {
isSurfaceValid.block();
} catch (InterruptedException e) {
break;
}
final SurfaceTexture surfaceTexture = getSurfaceTexture();
if (surfaceTexture == null) {
continue;
}
final Surface surface = new Surface(surfaceTexture);
try {
mGifInfoHandle.bindSurface(surface, mSavedState, isOpaque());
} finally {
surface.release();
}
}
mGifInfoHandle.recycle();
}
/**
* onClick handler for "play"/"stop" button.
*/
public void clickPlayStop(@SuppressWarnings("unused") View unused) {
if (mShowStopLabel) {
Log.d(TAG, "stopping movie");
stopPlayback();
// Don't update the controls here -- let the task thread do it after the movie has
// actually stopped.
//mShowStopLabel = false;
//updateControls();
} else {
if (mPlayTask != null) {
Log.w(TAG, "movie already playing");
return;
}
Log.d(TAG, "starting movie");
SpeedControlCallback callback = new SpeedControlCallback();
if (((CheckBox) findViewById(R.id.locked60fps_checkbox)).isChecked()) {
// TODO: consider changing this to be "free running" mode
callback.setFixedPlaybackRate(60);
}
SurfaceTexture st = mTextureView.getSurfaceTexture();
Surface surface = new Surface(st);
MoviePlayer player = null;
try {
player = new MoviePlayer(
new File(getFilesDir(), mMovieFiles[mSelectedMovie]), surface, callback);
} catch (IOException ioe) {
Log.e(TAG, "Unable to play movie", ioe);
surface.release();
return;
}
adjustAspectRatio(player.getVideoWidth(), player.getVideoHeight());
mPlayTask = new MoviePlayer.PlayTask(player, this);
if (((CheckBox) findViewById(R.id.loopPlayback_checkbox)).isChecked()) {
mPlayTask.setLoopMode(true);
}
mShowStopLabel = true;
updateControls();
mPlayTask.execute();
}
}
/**
* onClick handler for "play"/"stop" button.
*/
public void clickPlayStop(@SuppressWarnings("unused") View unused) {
if (mShowStopLabel) {
Log.d(TAG, "stopping movie");
stopPlayback();
// Don't update the controls here -- let the task thread do it after the movie has
// actually stopped.
//mShowStopLabel = false;
//updateControls();
} else {
if (mPlayTask != null) {
Log.w(TAG, "movie already playing");
return;
}
Log.d(TAG, "starting movie");
SpeedControlCallback callback = new SpeedControlCallback();
SurfaceHolder holder = mSurfaceView.getHolder();
Surface surface = holder.getSurface();
// Don't leave the last frame of the previous video hanging on the screen.
// Looks weird if the aspect ratio changes.
clearSurface(surface);
MoviePlayer player = null;
try {
player = new MoviePlayer(
new File(getFilesDir(), mMovieFiles[mSelectedMovie]), surface, callback);
} catch (IOException ioe) {
Log.e(TAG, "Unable to play movie", ioe);
surface.release();
return;
}
AspectFrameLayout layout = (AspectFrameLayout) findViewById(R.id.playMovie_afl);
int width = player.getVideoWidth();
int height = player.getVideoHeight();
layout.setAspectRatio((double) width / height);
//holder.setFixedSize(width, height);
mPlayTask = new MoviePlayer.PlayTask(player, this);
mShowStopLabel = true;
updateControls();
mPlayTask.execute();
}
}