Automatically destroy FlutterEngine when created by FlutterActivity or FlutterFragment. (flutter/engine#13423)

This commit is contained in:
Matt Carroll
2019-10-30 15:01:57 -07:00
committed by GitHub
parent 75c35fdfae
commit 14f2c142d2
5 changed files with 129 additions and 8 deletions

View File

@@ -20,6 +20,7 @@ import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
@@ -380,7 +381,8 @@ public class FlutterActivity extends Activity
// Delegate that runs all lifecycle and OS hook logic that is common between
// FlutterActivity and FlutterFragment. See the FlutterActivityAndFragmentDelegate
// implementation for details about why it exists.
private FlutterActivityAndFragmentDelegate delegate;
@VisibleForTesting
protected FlutterActivityAndFragmentDelegate delegate;
@NonNull
private LifecycleRegistry lifecycle;
@@ -389,6 +391,21 @@ public class FlutterActivity extends Activity
lifecycle = new LifecycleRegistry(this);
}
/**
* This method exists so that JVM tests can ensure that a delegate exists without
* putting this Activity through any lifecycle events, because JVM tests cannot handle
* executing any lifecycle methods, at the time of writing this.
* <p>
* The testing infrastructure should be upgraded to make FlutterActivity tests easy to
* write while exercising real lifecycle methods. At such a time, this method should be
* removed.
*/
// TODO(mattcarroll): remove this when tests allow for it (https://github.com/flutter/flutter/issues/43798)
@VisibleForTesting
/* package */ void setDelegate(@NonNull FlutterActivityAndFragmentDelegate delegate) {
this.delegate = delegate;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
switchLaunchThemeForNormalTheme();
@@ -674,7 +691,15 @@ public class FlutterActivity extends Activity
*/
@Override
public boolean shouldDestroyEngineWithHost() {
return getIntent().getBooleanExtra(EXTRA_DESTROY_ENGINE_WITH_ACTIVITY, false);
boolean explicitDestructionRequested = getIntent().getBooleanExtra(EXTRA_DESTROY_ENGINE_WITH_ACTIVITY, false);
if (getCachedEngineId() != null || delegate.isFlutterEngineFromHost()) {
// Only destroy a cached engine if explicitly requested by app developer.
return explicitDestructionRequested;
} else {
// If this Activity created the FlutterEngine, destroy it by default unless
// explicitly requested not to.
return getIntent().getBooleanExtra(EXTRA_DESTROY_ENGINE_WITH_ACTIVITY, true);
}
}
/**

View File

@@ -13,6 +13,7 @@ import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -121,10 +122,18 @@ import static android.content.ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
* or {@code Fragment}.
*/
@Nullable
FlutterEngine getFlutterEngine() {
/* package */ FlutterEngine getFlutterEngine() {
return flutterEngine;
}
/**
* Returns true if the host {@code Activity}/{@code Fragment} provided a
* {@code FlutterEngine}, as opposed to this delegate creating a new one.
*/
/* package */ boolean isFlutterEngineFromHost() {
return isFlutterEngineFromHost;
}
/**
* Invoke this method from {@code Activity#onCreate(Bundle)} or {@code Fragment#onAttach(Context)}.
* <p>
@@ -189,7 +198,8 @@ import static android.content.ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
* If the {@code host} does not provide a {@link FlutterEngine}, then a new {@link FlutterEngine}
* is instantiated.
*/
private void setupFlutterEngine() {
@VisibleForTesting
/* package */ void setupFlutterEngine() {
Log.d(TAG, "Setting up FlutterEngine.");
// First, check if the host wants to use a cached FlutterEngine.

View File

@@ -12,6 +12,7 @@ import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
@@ -565,7 +566,8 @@ public class FlutterFragment extends Fragment implements FlutterActivityAndFragm
// Delegate that runs all lifecycle and OS hook logic that is common between
// FlutterActivity and FlutterFragment. See the FlutterActivityAndFragmentDelegate
// implementation for details about why it exists.
private FlutterActivityAndFragmentDelegate delegate;
@VisibleForTesting
/* package */ FlutterActivityAndFragmentDelegate delegate;
public FlutterFragment() {
// Ensure that we at least have an empty Bundle of arguments so that we don't
@@ -573,6 +575,21 @@ public class FlutterFragment extends Fragment implements FlutterActivityAndFragm
setArguments(new Bundle());
}
/**
* This method exists so that JVM tests can ensure that a delegate exists without
* putting this Fragment through any lifecycle events, because JVM tests cannot handle
* executing any lifecycle methods, at the time of writing this.
* <p>
* The testing infrastructure should be upgraded to make FlutterFragment tests easy to
* write while exercising real lifecycle methods. At such a time, this method should be
* removed.
*/
// TODO(mattcarroll): remove this when tests allow for it (https://github.com/flutter/flutter/issues/43798)
@VisibleForTesting
/* package */ void setDelegate(@NonNull FlutterActivityAndFragmentDelegate delegate) {
this.delegate = delegate;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
@@ -766,7 +783,15 @@ public class FlutterFragment extends Fragment implements FlutterActivityAndFragm
*/
@Override
public boolean shouldDestroyEngineWithHost() {
return getArguments().getBoolean(ARG_DESTROY_ENGINE_WITH_FRAGMENT, false);
boolean explicitDestructionRequested = getArguments().getBoolean(ARG_DESTROY_ENGINE_WITH_FRAGMENT, false);
if (getCachedEngineId() != null || delegate.isFlutterEngineFromHost()) {
// Only destroy a cached engine if explicitly requested by app developer.
return explicitDestructionRequested;
} else {
// If this Fragment created the FlutterEngine, destroy it by default unless
// explicitly requested not to.
return getArguments().getBoolean(ARG_DESTROY_ENGINE_WITH_FRAGMENT, true);
}
}
/**

View File

@@ -1,6 +1,10 @@
package io.flutter.embedding.android;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -10,13 +14,18 @@ import org.robolectric.RuntimeEnvironment;
import org.robolectric.android.controller.ActivityController;
import org.robolectric.annotation.Config;
import io.flutter.embedding.android.FlutterActivityLaunchConfigs.BackgroundMode;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.FlutterJNI;
import io.flutter.embedding.engine.loader.FlutterLoader;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import io.flutter.embedding.android.FlutterActivityLaunchConfigs.BackgroundMode;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@Config(manifest=Config.NONE)
@RunWith(RobolectricTestRunner.class)
@@ -26,6 +35,7 @@ public class FlutterActivityTest {
Intent intent = FlutterActivity.createDefaultIntent(RuntimeEnvironment.application);
ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent);
FlutterActivity flutterActivity = activityController.get();
flutterActivity.setDelegate(new FlutterActivityAndFragmentDelegate(flutterActivity));
assertEquals("main", flutterActivity.getDartEntrypointFunctionName());
assertEquals("/", flutterActivity.getInitialRoute());
@@ -38,6 +48,32 @@ public class FlutterActivityTest {
assertEquals(FlutterView.TransparencyMode.opaque, flutterActivity.getTransparencyMode());
}
@Test
public void itDestroysNewEngineWhenIntentIsMissingParameter() {
// All clients should use the static members of FlutterActivity to construct an
// Intent. Missing extras is an error. However, Flutter has number of tests that
// don't seem to use the static members of FlutterActivity to construct the
// launching Intent, so this test explicitly verifies that even illegal Intents
// result in the automatic destruction of a non-cached FlutterEngine, which prevents
// the breakage of memory usage benchmark tests.
Intent intent = new Intent(RuntimeEnvironment.application, FlutterActivity.class);
ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent);
FlutterActivity flutterActivity = activityController.get();
flutterActivity.setDelegate(new FlutterActivityAndFragmentDelegate(flutterActivity));
assertTrue(flutterActivity.shouldDestroyEngineWithHost());
}
@Test
public void itDoesNotDestroyFlutterEngineWhenProvidedByHost() {
Intent intent = new Intent(RuntimeEnvironment.application, FlutterActivityWithProvidedEngine.class);
ActivityController<FlutterActivityWithProvidedEngine> activityController = Robolectric.buildActivity(FlutterActivityWithProvidedEngine.class, intent);
activityController.create();
FlutterActivityWithProvidedEngine flutterActivity = activityController.get();
assertFalse(flutterActivity.shouldDestroyEngineWithHost());
}
@Test
public void itCreatesNewEngineIntentWithRequestedSettings() {
Intent intent = FlutterActivity.withNewEngine()
@@ -46,6 +82,7 @@ public class FlutterActivityTest {
.build(RuntimeEnvironment.application);
ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent);
FlutterActivity flutterActivity = activityController.get();
flutterActivity.setDelegate(new FlutterActivityAndFragmentDelegate(flutterActivity));
assertEquals("/custom/route", flutterActivity.getInitialRoute());
assertArrayEquals(new String[]{}, flutterActivity.getFlutterShellArgs().toArray());
@@ -84,4 +121,26 @@ public class FlutterActivityTest {
assertEquals("my_cached_engine", flutterActivity.getCachedEngineId());
assertTrue(flutterActivity.shouldDestroyEngineWithHost());
}
static class FlutterActivityWithProvidedEngine extends FlutterActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.delegate = new FlutterActivityAndFragmentDelegate(this);
super.delegate.setupFlutterEngine();
}
@Nullable
@Override
public FlutterEngine provideFlutterEngine(@NonNull Context context) {
FlutterJNI flutterJNI = mock(FlutterJNI.class);
when(flutterJNI.isAttached()).thenReturn(true);
return new FlutterEngine(
context,
mock(FlutterLoader.class),
flutterJNI,
new String[]{}
);
}
}
}

View File

@@ -17,6 +17,7 @@ public class FlutterFragmentTest {
@Test
public void itCreatesDefaultFragmentWithExpectedDefaults() {
FlutterFragment fragment = FlutterFragment.createDefault();
fragment.setDelegate(new FlutterActivityAndFragmentDelegate(fragment));
assertEquals("main", fragment.getDartEntrypointFunctionName());
assertEquals("/", fragment.getInitialRoute());
@@ -37,6 +38,7 @@ public class FlutterFragmentTest {
.renderMode(FlutterView.RenderMode.texture)
.transparencyMode(FlutterView.TransparencyMode.opaque)
.build();
fragment.setDelegate(new FlutterActivityAndFragmentDelegate(fragment));
assertEquals("custom_entrypoint", fragment.getDartEntrypointFunctionName());
assertEquals("/custom/route", fragment.getInitialRoute());