[android] Fixes 'drawRenderNode called on a context with no surface' crash (flutter/engine#33655)

This commit is contained in:
Rulong Chen(陈汝龙)
2022-06-13 18:58:05 +08:00
committed by GitHub
parent 7a8d213e63
commit e915cd6a6b
7 changed files with 190 additions and 52 deletions

View File

@@ -844,24 +844,10 @@ import java.util.List;
flutterEngine.getDartExecutor().notifyLowMemoryWarning();
flutterEngine.getSystemChannel().sendMemoryPressureWarning();
}
flutterEngine.getRenderer().onTrimMemory(level);
}
}
/**
* Invoke this from {@link android.app.Activity#onLowMemory()}.
*
* <p>A {@code Fragment} host must have its containing {@code Activity} forward this call so that
* the {@code Fragment} can then invoke this method.
*
* <p>This method sends a "memory pressure warning" message to Flutter over the "system channel".
*/
void onLowMemory() {
Log.v(TAG, "Forwarding onLowMemory() to FlutterEngine.");
ensureAlive();
flutterEngine.getDartExecutor().notifyLowMemoryWarning();
flutterEngine.getSystemChannel().sendMemoryPressureWarning();
}
/**
* Ensures that this delegate has not been {@link #release()}'ed.
*

View File

@@ -980,19 +980,6 @@ public class FlutterFragment extends Fragment
}
}
/**
* Callback invoked when memory is low.
*
* <p>This implementation forwards a memory pressure warning to the running Flutter app.
*/
@Override
public void onLowMemory() {
super.onLowMemory();
if (stillAttachedForEvent("onLowMemory")) {
delegate.onLowMemory();
}
}
/**
* {@link FlutterActivityAndFragmentDelegate.Host} method that is used by {@link
* FlutterActivityAndFragmentDelegate} to obtain Flutter shell arguments when initializing

View File

@@ -12,12 +12,17 @@ import android.os.Handler;
import android.view.Surface;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import io.flutter.Log;
import io.flutter.embedding.engine.FlutterJNI;
import io.flutter.view.TextureRegistry;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
/**
@@ -42,6 +47,10 @@ public class FlutterRenderer implements TextureRegistry {
private boolean isDisplayingFlutterUi = false;
private Handler handler = new Handler();
@NonNull
private final Set<WeakReference<TextureRegistry.OnTrimMemoryListener>> onTrimMemoryListeners =
new HashSet<>();
@NonNull
private final FlutterUiDisplayListener flutterUiDisplayListener =
new FlutterUiDisplayListener() {
@@ -89,6 +98,39 @@ public class FlutterRenderer implements TextureRegistry {
flutterJNI.removeIsDisplayingFlutterUiListener(listener);
}
private void clearDeadListeners() {
final Iterator<WeakReference<OnTrimMemoryListener>> iterator = onTrimMemoryListeners.iterator();
while (iterator.hasNext()) {
WeakReference<OnTrimMemoryListener> listenerRef = iterator.next();
final OnTrimMemoryListener listener = listenerRef.get();
if (listener == null) {
iterator.remove();
}
}
}
/** Adds a listener that is invoked when a memory pressure warning was forward. */
@VisibleForTesting
/* package */ void addOnTrimMemoryListener(@NonNull OnTrimMemoryListener listener) {
// Purge dead listener to avoid accumulating.
clearDeadListeners();
onTrimMemoryListeners.add(new WeakReference<>(listener));
}
/**
* Removes a {@link OnTrimMemoryListener} that was added with {@link
* #addOnTrimMemoryListener(OnTrimMemoryListener)}.
*/
@VisibleForTesting
/* package */ void removeOnTrimMemoryListener(@NonNull OnTrimMemoryListener listener) {
for (WeakReference<OnTrimMemoryListener> listenerRef : onTrimMemoryListeners) {
if (listenerRef.get() == listener) {
onTrimMemoryListeners.remove(listenerRef);
break;
}
}
}
// ------ START TextureRegistry IMPLEMENTATION -----
/**
* Creates and returns a new {@link SurfaceTexture} managed by the Flutter engine that is also
@@ -112,20 +154,38 @@ public class FlutterRenderer implements TextureRegistry {
new SurfaceTextureRegistryEntry(nextTextureId.getAndIncrement(), surfaceTexture);
Log.v(TAG, "New SurfaceTexture ID: " + entry.id());
registerTexture(entry.id(), entry.textureWrapper());
addOnTrimMemoryListener(entry);
return entry;
}
final class SurfaceTextureRegistryEntry implements TextureRegistry.SurfaceTextureEntry {
@Override
public void onTrimMemory(int level) {
final Iterator<WeakReference<OnTrimMemoryListener>> iterator = onTrimMemoryListeners.iterator();
while (iterator.hasNext()) {
WeakReference<OnTrimMemoryListener> listenerRef = iterator.next();
final OnTrimMemoryListener listener = listenerRef.get();
if (listener != null) {
listener.onTrimMemory(level);
} else {
// Purge cleared refs to avoid accumulating a lot of dead listener
iterator.remove();
}
}
}
final class SurfaceTextureRegistryEntry
implements TextureRegistry.SurfaceTextureEntry, TextureRegistry.OnTrimMemoryListener {
private final long id;
@NonNull private final SurfaceTextureWrapper textureWrapper;
private boolean released;
@Nullable private OnFrameConsumedListener listener;
@Nullable private OnTrimMemoryListener trimMemoryListener;
@Nullable private OnFrameConsumedListener frameConsumedListener;
private final Runnable onFrameConsumed =
new Runnable() {
@Override
public void run() {
if (listener != null) {
listener.onFrameConsumed();
if (frameConsumedListener != null) {
frameConsumedListener.onFrameConsumed();
}
}
};
@@ -149,6 +209,13 @@ public class FlutterRenderer implements TextureRegistry {
}
}
@Override
public void onTrimMemory(int level) {
if (trimMemoryListener != null) {
trimMemoryListener.onTrimMemory(level);
}
}
private SurfaceTexture.OnFrameAvailableListener onFrameListener =
new SurfaceTexture.OnFrameAvailableListener() {
@Override
@@ -164,6 +231,10 @@ public class FlutterRenderer implements TextureRegistry {
}
};
private void removeListener() {
removeOnTrimMemoryListener(this);
}
@NonNull
public SurfaceTextureWrapper textureWrapper() {
return textureWrapper;
@@ -188,6 +259,7 @@ public class FlutterRenderer implements TextureRegistry {
Log.v(TAG, "Releasing a SurfaceTexture (" + id + ").");
textureWrapper.release();
unregisterTexture(id);
removeListener();
released = true;
}
@@ -206,7 +278,12 @@ public class FlutterRenderer implements TextureRegistry {
@Override
public void setOnFrameConsumedListener(@Nullable OnFrameConsumedListener listener) {
this.listener = listener;
frameConsumedListener = listener;
}
@Override
public void setOnTrimMemoryListener(@Nullable OnTrimMemoryListener listener) {
trimMemoryListener = listener;
}
}

View File

@@ -4,6 +4,8 @@
package io.flutter.plugin.platform;
import static android.content.ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
@@ -56,7 +58,7 @@ class PlatformViewWrapper extends FrameLayout {
@Nullable @VisibleForTesting ViewTreeObserver.OnGlobalFocusChangeListener activeFocusListener;
private final AtomicLong pendingFramesCount = new AtomicLong(0L);
private final TextureRegistry.OnFrameConsumedListener listener =
private final TextureRegistry.OnFrameConsumedListener frameConsumedListener =
new TextureRegistry.OnFrameConsumedListener() {
@Override
public void onFrameConsumed() {
@@ -66,12 +68,40 @@ class PlatformViewWrapper extends FrameLayout {
}
};
private boolean shouldRecreateSurfaceForLowMemory = false;
private final TextureRegistry.OnTrimMemoryListener trimMemoryListener =
new TextureRegistry.OnTrimMemoryListener() {
@Override
public void onTrimMemory(int level) {
// When a memory pressure warning is received and the level equal {@code
// ComponentCallbacks2.TRIM_MEMORY_COMPLETE}, the Android system releases the underlying
// surface. If we continue to use the surface (e.g., call lockHardwareCanvas), a crash
// occurs, and we found that this crash appeared on Android10 and above.
// See https://github.com/flutter/flutter/issues/103870 for more details.
//
// Here our workaround is to recreate the surface before using it.
if (level == TRIM_MEMORY_COMPLETE && Build.VERSION.SDK_INT >= 29) {
shouldRecreateSurfaceForLowMemory = true;
}
}
};
private void onFrameProduced() {
if (Build.VERSION.SDK_INT == 29) {
pendingFramesCount.incrementAndGet();
}
}
private void recreateSurfaceIfNeeded() {
if (shouldRecreateSurfaceForLowMemory) {
if (surface != null) {
surface.release();
}
surface = createSurface(tx);
shouldRecreateSurfaceForLowMemory = false;
}
}
private boolean shouldDrawToSurfaceNow() {
if (Build.VERSION.SDK_INT == 29) {
return pendingFramesCount.get() <= 0L;
@@ -87,7 +117,8 @@ class PlatformViewWrapper extends FrameLayout {
public PlatformViewWrapper(
@NonNull Context context, @NonNull TextureRegistry.SurfaceTextureEntry textureEntry) {
this(context);
textureEntry.setOnFrameConsumedListener(listener);
textureEntry.setOnFrameConsumedListener(frameConsumedListener);
textureEntry.setOnTrimMemoryListener(trimMemoryListener);
setTexture(textureEntry.surfaceTexture());
}
@@ -249,6 +280,10 @@ class PlatformViewWrapper extends FrameLayout {
// If there are still frames that are not consumed, we will draw them next time.
invalidate();
} else {
// We try to recreate the surface before using it to avoid the crash:
// https://github.com/flutter/flutter/issues/103870
recreateSurfaceIfNeeded();
// Override the canvas that this subtree of views will use to draw.
final Canvas surfaceCanvas = surface.lockHardwareCanvas();
try {

View File

@@ -31,6 +31,13 @@ public interface TextureRegistry {
@NonNull
SurfaceTextureEntry registerSurfaceTexture(@NonNull SurfaceTexture surfaceTexture);
/**
* Callback invoked when memory is low.
*
* <p>Invoke this from {@link android.app.Activity#onTrimMemory(int)}.
*/
default void onTrimMemory(int level) {}
/** A registry entry for a managed SurfaceTexture. */
interface SurfaceTextureEntry {
/** @return The managed SurfaceTexture. */
@@ -45,6 +52,9 @@ public interface TextureRegistry {
/** Set a listener that will be notified when the most recent image has been consumed. */
default void setOnFrameConsumedListener(@Nullable OnFrameConsumedListener listener) {}
/** Set a listener that will be notified when a memory pressure warning was forward. */
default void setOnTrimMemoryListener(@Nullable OnTrimMemoryListener listener) {}
}
/** Listener invoked when the most recent image has been consumed. */
@@ -55,4 +65,10 @@ public interface TextureRegistry {
*/
void onFrameConsumed();
}
/** Listener invoked when a memory pressure warning was forward. */
interface OnTrimMemoryListener {
/** This method will be invoked when a memory pressure warning was forward. */
void onTrimMemory(int level);
}
}

View File

@@ -863,23 +863,6 @@ public class FlutterActivityAndFragmentDelegateTest {
verify(mockFlutterEngine.getSystemChannel(), times(6)).sendMemoryPressureWarning();
}
@Test
public void itNotifiesDartExecutorAndSendsMessageOverSystemChannelWhenInformedOfLowMemory() {
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is set up in onAttach().
delegate.onAttach(ctx);
// Emulate the host and call the method that we expect to be forwarded.
delegate.onLowMemory();
// Verify that the call was forwarded to the engine.
verify(mockFlutterEngine.getDartExecutor(), times(1)).notifyLowMemoryWarning();
verify(mockFlutterEngine.getSystemChannel(), times(1)).sendMemoryPressureWarning();
}
@Test
public void itDestroysItsOwnEngineIfHostRequestsIt() {
// ---- Test setup ----

View File

@@ -1,5 +1,6 @@
package io.flutter.embedding.engine.renderer;
import static android.content.ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anyFloat;
@@ -7,6 +8,7 @@ import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -339,4 +341,56 @@ public class FlutterRendererTest {
// Verify behavior under test.
assertEquals(1, invocationCount.get());
}
@Test
public void itAddsListenerWhenSurfaceTextureEntryCreated() {
// Setup the test.
FlutterRenderer flutterRenderer = spy(new FlutterRenderer(fakeFlutterJNI));
// Execute the behavior under test.
FlutterRenderer.SurfaceTextureRegistryEntry entry =
(FlutterRenderer.SurfaceTextureRegistryEntry) flutterRenderer.createSurfaceTexture();
// Verify behavior under test.
verify(flutterRenderer, times(1)).addOnTrimMemoryListener(entry);
}
@Test
public void itRemovesListenerWhenSurfaceTextureEntryReleased() {
// Setup the test.
FlutterRenderer flutterRenderer = spy(new FlutterRenderer(fakeFlutterJNI));
FlutterRenderer.SurfaceTextureRegistryEntry entry =
(FlutterRenderer.SurfaceTextureRegistryEntry) flutterRenderer.createSurfaceTexture();
// Execute the behavior under test.
entry.release();
// Verify behavior under test.
verify(flutterRenderer, times(1)).removeOnTrimMemoryListener(entry);
}
@Test
public void itNotifySurfaceTextureEntryWhenMemoryPressureWarning() {
// Setup the test.
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
AtomicInteger invocationCount = new AtomicInteger(0);
final TextureRegistry.OnTrimMemoryListener listener =
new TextureRegistry.OnTrimMemoryListener() {
@Override
public void onTrimMemory(int level) {
invocationCount.incrementAndGet();
}
};
FlutterRenderer.SurfaceTextureRegistryEntry entry =
(FlutterRenderer.SurfaceTextureRegistryEntry) flutterRenderer.createSurfaceTexture();
entry.setOnTrimMemoryListener(listener);
// Execute the behavior under test.
flutterRenderer.onTrimMemory(TRIM_MEMORY_COMPLETE);
// Verify behavior under test.
assertEquals(1, invocationCount.get());
}
}