@ SuppressWarnings ( "unchecked" ) public ActivityController < T > recreate ( ) { Stage originalStage = ActivityLifecycleMonitorRegistry . getInstance ( ) . getLifecycleStageOf ( component ) ; switch ( originalStage ) { case PRE_ON_CREATE : create ( ) ; // fall through case CREATED : case RESTARTED : start ( ) ; postCreate ( null ) ; // fall through case STARTED : resume ( ) ; // fall through case RESUMED : pause ( ) ; // fall through case PAUSED : stop ( ) ; // fall through case STOPPED : break ; default : throw new IllegalStateException ( "Cannot recreate activity since it's destroyed already" ) ; } // Activity#mChangingConfigurations flag should be set prior to Activity recreation process // starts. ActivityThread does set it on real device but here we simulate the Activity // recreation process on behalf of ActivityThread so set the flag here. Note we don't need to // reset the flag to false because this Activity instance is going to be destroyed and disposed. // https://android.googlesource.com/platform/frameworks/base/+/55418eada51d4f5e6532ae9517af66c50 // ea495c4/core/java/android/app/ActivityThread.java#4806 ReflectionHelpers . setField ( component , "mChangingConfigurations" , true ) ; Bundle outState = new Bundle ( ) ; saveInstanceState ( outState ) ; Object lastNonConfigurationInstances = ReflectionHelpers . callInstanceMethod ( component , "retainNonConfigurationInstances" ) ; destroy ( ) ; component = ( T ) ReflectionHelpers . callConstructor ( component . getClass ( ) ) ; _component_ = reflector ( _Activity_ . class , component ) ; attached = false ; attach ( lastNonConfigurationInstances ) ; create ( outState ) ; start ( ) ; restoreInstanceState ( outState ) ; postCreate ( outState ) ; resume ( ) ; postResume ( ) ; visible ( ) ; windowFocusChanged ( true ) ; // Move back to the original stage. If the original stage was transient stage, it will bring it // to resumed state to match the on device behavior. switch ( originalStage ) { case PAUSED : pause ( ) ; return this ; case STOPPED : pause ( ) ; stop ( ) ; return this ; default : return this ; } }
Recreates activity instance which is controlled by this ActivityController . NonConfigurationInstances and savedInstanceStateBundle are properly passed into a new instance . After the recreation it brings back its lifecycle state to the original state . The activity should not be destroyed yet .