Repository: flutter
Issue: When using FlutterEngineGroup on Android to display Google Maps, the app crashes when trying to return from destroying the Activity.
Labels: c: crash,platform-android,p: maps,package,has reproducible steps,P2,team-android,triaged-android,found in release: 3.22,found in release: 3.24

### Steps to reproduce

1. Displaying a GoogleMap using FlutterEngineGroup in a sample project.
2. Put the app into background.
3. At this time, the Activity that is drawing the Flutter screen will be destroyed. (Set up don`t keep Activities in Developer Options.)
4. Restart the app.

You can see the sample project below.

<details close>
<summary>Android sample code</summary>

```kotlin
// application class.
class SampleApplication : Application() {
    var engineGroup: FlutterEngineGroup? = null
    override fun onCreate() {
        super.onCreate()
        engineGroup = FlutterEngineGroup(this)
        val mainFlutterEngine = engineGroup!!.createAndRunDefaultEngine(this)
        FlutterEngineCache.getInstance().put("main", mainFlutterEngine)
    }
}

```

```kotlin
class InitializeActivity : Activity() {
    override fun onResume() {
        super.onResume()
        // ..run initialization process
        val enginId = "main"
        if (!FlutterEngineCache.getInstance().contains(enginId)) {
            val mainFlutterEngine = (application as SampleApplication).engineGroup?.createAndRunDefaultEngine(this)
            FlutterEngineCache.getInstance().put("main", mainFlutterEngine)
        }
        startActivity(FlutterActivity.CachedEngineIntentBuilder(MainActivity::class.java, enginId).build(this))
        finish()
    }
}
```

```kotlin
class MainActivity : FlutterActivity() {}
```

```xml
<!--AndroidManifest-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application
        android:name=".SampleApplication"
        android:icon="@mipmap/ic_launcher"
        android:label="try_google_map_activity_disposed">
        <activity
            android:name=".MainActivity"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:exported="true"
            android:hardwareAccelerated="true"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:windowSoftInputMode="adjustResize">
            <meta-data
                android:name="io.flutter.embedding.android.NormalTheme"
                android:resource="@style/NormalTheme" />
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <activity
            android:name=".InitializeActivity"
            android:exported="true"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="your api key" />
    </application>
    <!-- Required to query activities that can process text, see:
         https://developer.android.com/training/package-visibility and
         https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.

         In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
    <queries>
        <intent>
            <action android:name="android.intent.action.PROCESS_TEXT" />
            <data android:mimeType="text/plain" />
        </intent>
    </queries>
</manifest>
```
</details>

<details close>
<summary>Flutter Sample Code</summary>

```dart
Future<void> main() async {
  final GoogleMapsFlutterPlatform mapsImplementation =
      GoogleMapsFlutterPlatform.instance;
  if (mapsImplementation is GoogleMapsFlutterAndroid) {
    mapsImplementation.useAndroidViewSurface = false;
    WidgetsFlutterBinding.ensureInitialized();
    // GoogleMap Renderer Settings. legacy or latest.
    await mapsImplementation.initializeWithRenderer(AndroidMapRenderer.latest);
  }

  runApp(const MaterialApp(home: MapSample()));
}

class MapSample extends StatefulWidget {
  const MapSample({super.key});

  @override
  State<MapSample> createState() => MapSampleState();
}

class MapSampleState extends State<MapSample> {

  static const CameraPosition _kGooglePlex = CameraPosition(
    target: LatLng(37.42796133580664, -122.085749655962),
    zoom: 14.4746,
  );

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: GoogleMap(
        mapType: MapType.normal,
        initialCameraPosition: _kGooglePlex,
      ),
    );
  }
}
```

</details>

The version of google_maps_flutter used in the sample is 2.5.3.

### Actual results

The application crashes when returning from destroying the activity.
On some devices the GoogleMap doesn't draw without the app crashing.

<details close>
<summary>An example of when GoogleMap is displayed without crashing.</summary>

<video src=https://github.com/user-attachments/assets/b6dccc2d-eaf1-427f-b542-239f81515bab width=320>


</details>

### Logs

<details close>
<summary>Crash Logs</summary>

```console
D/AndroidRuntime(16889): Shutting down VM
E/AndroidRuntime(16889): FATAL EXCEPTION: main
E/AndroidRuntime(16889): Process: com.example.try_google_map_activity_disposed, PID: 16889
E/AndroidRuntime(16889): java.lang.RuntimeException: Unable to resume activity {com.example.try_google_map_activity_disposed/com.example.try_google_map_activity_disposed.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.view.View.isFocused()' on a null object reference
E/AndroidRuntime(16889): 	at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4773)
E/AndroidRuntime(16889): 	at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4806)
E/AndroidRuntime(16889): 	at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:54)
E/AndroidRuntime(16889): 	at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
E/AndroidRuntime(16889): 	at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
E/AndroidRuntime(16889): 	at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
E/AndroidRuntime(16889): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)
E/AndroidRuntime(16889): 	at android.os.Handler.dispatchMessage(Handler.java:106)
E/AndroidRuntime(16889): 	at android.os.Looper.loopOnce(Looper.java:201)
E/AndroidRuntime(16889): 	at android.os.Looper.loop(Looper.java:288)
E/AndroidRuntime(16889): 	at android.app.ActivityThread.main(ActivityThread.java:7872)
E/AndroidRuntime(16889): 	at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(16889): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
E/AndroidRuntime(16889): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
E/AndroidRuntime(16889): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.view.View.isFocused()' on a null object reference
E/AndroidRuntime(16889): 	at io.flutter.plugin.platform.VirtualDisplayController.resetSurface(VirtualDisplayController.java:294)
E/AndroidRuntime(16889): 	at io.flutter.plugin.platform.PlatformViewsController.onResume(PlatformViewsController.java:1071)
E/AndroidRuntime(16889): 	at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onPostResume(FlutterActivityAndFragmentDelegate.java:586)
E/AndroidRuntime(16889): 	at io.flutter.embedding.android.FlutterActivity.onPostResume(FlutterActivity.java:833)
E/AndroidRuntime(16889): 	at android.app.Activity.performResume(Activity.java:8462)
E/AndroidRuntime(16889): 	at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4763)
E/AndroidRuntime(16889): 	... 13 more
```

</details>


### Flutter Doctor output

<details close>
<summary>Doctor output</summary>

```console
[✓] Flutter (Channel stable, 3.22.0, on macOS 14.4.1 23E224 darwin-arm64, locale ja-JP)
    • Flutter version 3.22.0 on channel stable at /Users/fvm/versions/3.22.0
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 5dcb86f68f (3 months ago), 2024-05-09 07:39:20 -0500
    • Engine revision f6344b75dc
    • Dart version 3.4.0
    • DevTools version 2.34.3

[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
    • Android SDK at /Users/Library/Android/sdk
    • Platform android-34, build-tools 34.0.0
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b829.9-10027231)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 15.4)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 15F31d
    • CocoaPods version 1.15.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2022.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b829.9-10027231)

[✓] VS Code (version 1.77.1)
    • VS Code at /Users/Downloads/Visual Studio Code.app/Contents
    • Flutter extension can be installed from:
      🔨 https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[✓] Connected device (5 available)
    • FCG01 (mobile)                  • 94ad31d3              • android-arm64  • Android 13 (API 33)
    • sdk gphone64 arm64 (mobile)     • emulator-5556         • android-arm64  • Android 13 (API 33) (emulator)
    • macOS (desktop)                 • macos                 • darwin-arm64   • macOS 14.4.1 23E224 darwin-arm64
    • Mac Designed for iPad (desktop) • mac-designed-for-ipad • darwin         • macOS 14.4.1 23E224 darwin-arm64
    • Chrome (web)                    • chrome                • web-javascript • Google Chrome 126.0.6478.185

[✓] Network resources
    • All expected network resources are available.

• No issues found!
```

</details>