Repository: flutter
Issue: [Add2App][Android][Crash] FlutterFragment crash by activity / fragment recycled
Labels: c: crash,platform-android,engine,a: existing-apps,has reproducible steps,P2,found in release: 3.0,found in release: 3.1,team-android,triaged-android

<!-- Thank you for using Flutter!

     If you are looking for support, please check out our documentation
     or consider asking a question on Stack Overflow:
      * https://flutter.dev/
      * https://api.flutter.dev/
      * https://stackoverflow.com/questions/tagged/flutter?sort=frequent

     If you have found a bug or if our documentation doesn't have an answer
     to what you're looking for, then fill out the template below. Please read
     our guide to filing a bug first: https://flutter.dev/docs/resources/bug-reports
-->
Our App got a lot of crashes while doing flutter migration. The stack trace as below
```
Caused by java.lang.NullPointerException
Attempt to invoke virtual method 'void io.flutter.embedding.android.m.e()' on a null object reference

===========================================
io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onDestroyView (FlutterActivityAndFragmentDelegate.java:613)
io.flutter.embedding.android.FlutterFragment.detachFromFlutterEngine (FlutterFragment.java:869)
io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.detachFromFlutterEngine (FlutterActivityAndFragmentDelegate.java:649)
io.flutter.embedding.engine.FlutterEngineConnectionRegistry.attachToActivity (FlutterEngineConnectionRegistry.java:319)
io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onAttach (FlutterActivityAndFragmentDelegate.java:189)
```


## Steps to Reproduce

<!-- Please include full steps to reproduce so that we can reproduce the problem. -->

1. clone code sample from [crash_demo](https://github.com/bradchien/crash_demo) <!-- (see "Code sample" section below) -->
2. before run demo, turn on `Don't keep activities` in android settings > system > developer options > apps <!-- describe steps to demonstrate bug -->
3. run app, fast switch apps by swiping system navigation bar <!-- for example "Tap on X and see a crash" -->
(you could follow the steps as [demo video](https://drive.google.com/file/d/1lGIuHS5aHCX3VQoQSf7wsPYisOy5RgE6/view?usp=sharing) shown)

**Expected results:** <!-- what did you want to see? -->
App could restore without any error.

**Actual results:** <!-- what did you see? -->
App crash randomly while restoring activity with flutter fragment.

<details>
<summary>Code sample</summary>

<!--
      Please create a minimal reproducible sample that shows the problem
      and attach it below between the lines with the backticks.

      To create it you can use `flutter create bug` command and update the `main.dart` file.

      Alternatively, you can use https://dartpad.dev/
      which is capable of creating and running small Flutter apps.

      Without this we will unlikely be able to progress on the issue, and because of that
      we regretfully will have to close it.
-->

```kotlin
	override fun onCreate(savedInstanceState: Bundle?) {
		engineBindings.attach()

		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_main)

		flutterFragment =
			FlutterFragment.withCachedEngine("shared_engine").renderMode(RenderMode.texture).build()
		val transaction = supportFragmentManager.beginTransaction()
		transaction.add(R.id.container, flutterFragment!!, "Flutter_Page")
		transaction.commit()
	}

	override fun onDestroy() {
		super.onDestroy()
		engineBindings.detach()
	}
```
and implement event handler from the tutorial [Adding a Flutter Fragment to an Android app](https://docs.flutter.dev/development/add-to-app/android/add-flutter-fragment?tab=forward-activity-calls-kotlin-tab)

</details>

<details>
  <summary>Logs</summary>

<!--
      Run your application with `flutter run --verbose` and attach all the
      log output below between the lines with the backticks. If there is an
      exception, please see if the error message includes enough information
      to explain how to solve the issue. If there is a crash, please include
      the entirety of the crash log including the backtrace.
-->

```
FATAL EXCEPTION: main
Process: dev.flutter.multipleflutters, PID: 24902
java.lang.RuntimeException: Unable to start activity ComponentInfo{dev.flutter.multipleflutters/dev.flutter.multipleflutters.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void io.flutter.embedding.android.FlutterView.detachFromFlutterEngine()' on a null object reference
	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3635)
	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
	at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
	at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
	at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
	at android.os.Handler.dispatchMessage(Handler.java:106)
	at android.os.Looper.loopOnce(Looper.java:201)
	at android.os.Looper.loop(Looper.java:288)
	at android.app.ActivityThread.main(ActivityThread.java:7839)
	at java.lang.reflect.Method.invoke(Native Method)
	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void io.flutter.embedding.android.FlutterView.detachFromFlutterEngine()' on a null object reference
	at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onDestroyView(FlutterActivityAndFragmentDelegate.java:613)
	at io.flutter.embedding.android.FlutterFragment.detachFromFlutterEngine(FlutterFragment.java:869)
	at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.detachFromFlutterEngine(FlutterActivityAndFragmentDelegate.java:649)
	at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.attachToActivity(FlutterEngineConnectionRegistry.java:319)
	at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onAttach(FlutterActivityAndFragmentDelegate.java:189)
	at io.flutter.embedding.android.FlutterFragment.onAttach(FlutterFragment.java:777)
	at androidx.fragment.app.Fragment.performAttach(Fragment.java:2574)
	at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:828)
	at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
	at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
	at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2659)
	at androidx.fragment.app.FragmentManagerImpl.dispatchCreate(FragmentManagerImpl.java:2607)
	at androidx.fragment.app.FragmentController.dispatchCreate(FragmentController.java:235)
	at androidx.fragment.app.FragmentActivity.onCreate(FragmentActivity.java:316)
	at androidx.appcompat.app.AppCompatActivity.onCreate(AppCompatActivity.java:106)
	at dev.flutter.multipleflutters.MainActivity.onCreate(MainActivity.kt:24)
	at android.app.Activity.performCreate(Activity.java:8050)
	at android.app.Activity.performCreate(Activity.java:8030)
	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3608)
	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792) 
	at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) 
	at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
	at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210) 
	at android.os.Handler.dispatchMessage(Handler.java:106) 
	at android.os.Looper.loopOnce(Looper.java:201) 
	at android.os.Looper.loop(Looper.java:288) 
	at android.app.ActivityThread.main(ActivityThread.java:7839) 
	at java.lang.reflect.Method.invoke(Native Method) 
	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) 
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 
```

<!--
     Run `flutter analyze` and attach any output of that command below.
     If there are any analysis errors, try resolving them before filing this issue.
-->

```
```

<!-- Finally, paste the output of running `flutter doctor -v` here. -->

```
[✓] Flutter (Channel stable, 3.0.5, on macOS 12.2.1 21D62 darwin-arm, locale zh-Hant-TW)
    • Flutter version 3.0.5 at /Users/bradchien/development/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision f1875d570e (6 weeks ago), 2022-07-13 11:24:16 -0700
    • Engine revision e85ea0e79c
    • Dart version 2.17.6
    • DevTools version 2.12.2

[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    • Android SDK at /Users/bradchien/Library/Android/sdk
    • Platform android-32, build-tools 32.1.0-rc1
    • Java binary at: /Applications/Android Studio Preview.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.4.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio
    • Android Studio at /Applications/Android Studio Preview.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 11.0.13+0-b1751.21-8125866)

[✓] Connected device (4 available)
    • Pixel 6 (mobile)            • 1A021FDF6008KX            • android-arm64  • Android 12 (API 31)
    • KKTV iPhone 11 Pro (mobile) • 00008030-001139100E00802E • ios            • iOS 15.6 19G71
    • macOS (desktop)             • macos                     • darwin-arm64   • macOS 12.2.1 21D62 darwin-arm
    • Chrome (web)                • chrome                    • web-javascript • Google Chrome 104.0.5112.101
    ! Error: 遙遠的TV is not connected. Xcode will continue when 遙遠的TV is connected. (code -13)

[✓] HTTP Host Availability
    • All required HTTP hosts are available
```

</details>


<!--
      Consider also attaching screenshots and/or videos to better
      illustrate the issue.

      You can upload them directly on GitHub.
      Beware that video file size is limited to 10MB.
-->