Home | History | Annotate | Download | only in lifecycle
      1 /*
      2  * Copyright (C) 2017 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package androidx.lifecycle;
     18 
     19 import android.app.Activity;
     20 import android.app.Application;
     21 import android.content.Context;
     22 import android.os.Bundle;
     23 
     24 import androidx.annotation.VisibleForTesting;
     25 
     26 import java.util.concurrent.atomic.AtomicBoolean;
     27 
     28 /**
     29  * When initialized, it hooks into the Activity callback of the Application and observes
     30  * Activities. It is responsible to hook in child-fragments to activities and fragments to report
     31  * their lifecycle events. Another responsibility of this class is to mark as stopped all lifecycle
     32  * providers related to an activity as soon it is not safe to run a fragment transaction in this
     33  * activity.
     34  */
     35 class LifecycleDispatcher {
     36 
     37     private static AtomicBoolean sInitialized = new AtomicBoolean(false);
     38 
     39     static void init(Context context) {
     40         if (sInitialized.getAndSet(true)) {
     41             return;
     42         }
     43         ((Application) context.getApplicationContext())
     44                 .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
     45     }
     46 
     47     @SuppressWarnings("WeakerAccess")
     48     @VisibleForTesting
     49     static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
     50 
     51         @Override
     52         public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
     53             ReportFragment.injectIfNeededIn(activity);
     54         }
     55 
     56         @Override
     57         public void onActivityStopped(Activity activity) {
     58         }
     59 
     60         @Override
     61         public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
     62         }
     63     }
     64 
     65     private LifecycleDispatcher() {
     66     }
     67 }
     68