summaryrefslogtreecommitdiff
path: root/main/java/com/google/android/setupcompat/internal/LifecycleFragment.java
blob: 269dd6dd4329708313ef2e4215a420d2a4a4f9d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.android.setupcompat.internal;

import static java.util.concurrent.TimeUnit.NANOSECONDS;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.util.Log;
import com.google.android.setupcompat.logging.MetricKey;
import com.google.android.setupcompat.logging.SetupMetricsLogger;
import com.google.android.setupcompat.util.WizardManagerHelper;

/** Fragment used to detect lifecycle of an activity for metrics logging. */
public class LifecycleFragment extends Fragment {
  private static final String LOG_TAG = LifecycleFragment.class.getSimpleName();
  private static final String FRAGMENT_ID = "lifecycle_monitor";

  private MetricKey metricKey;
  private long startInNanos;
  private long durationInNanos = 0;

  public LifecycleFragment() {
    setRetainInstance(true);
  }

  /**
   * Attaches the lifecycle fragment if it is not attached yet.
   *
   * @param activity the activity to detect lifecycle for.
   * @return fragment to monitor life cycle.
   */
  public static LifecycleFragment attachNow(Activity activity) {
    if (WizardManagerHelper.isAnySetupWizard(activity.getIntent())) {
      SetupCompatServiceInvoker.get(activity.getApplicationContext())
          .bindBack(
              LayoutBindBackHelper.getScreenName(activity),
              LayoutBindBackHelper.getExtraBundle(activity));

      if (VERSION.SDK_INT > VERSION_CODES.M) {
        FragmentManager fragmentManager = activity.getFragmentManager();
        if (fragmentManager != null && !fragmentManager.isDestroyed()) {
          Fragment fragment = fragmentManager.findFragmentByTag(FRAGMENT_ID);
          if (fragment == null) {
            LifecycleFragment lifeCycleFragment = new LifecycleFragment();
            try {
              fragmentManager.beginTransaction().add(lifeCycleFragment, FRAGMENT_ID).commitNow();
              fragment = lifeCycleFragment;
            } catch (IllegalStateException e) {
              Log.e(
                  LOG_TAG,
                  "Error occurred when attach to Activity:" + activity.getComponentName(),
                  e);
            }
          } else if (!(fragment instanceof LifecycleFragment)) {
            Log.wtf(
                LOG_TAG,
                activity.getClass().getSimpleName() + " Incorrect instance on lifecycle fragment.");
            return null;
          }
          return (LifecycleFragment) fragment;
        }
      }
    }

    return null;
  }

  @Override
  public void onAttach(Context context) {
    super.onAttach(context);
    metricKey = MetricKey.get("ScreenDuration", getActivity().getClass().getSimpleName());
  }

  @Override
  public void onDetach() {
    super.onDetach();
    SetupMetricsLogger.logDuration(getActivity(), metricKey, NANOSECONDS.toMillis(durationInNanos));
  }

  @Override
  public void onResume() {
    super.onResume();
    startInNanos = ClockProvider.timeInNanos();
  }

  @Override
  public void onPause() {
    super.onPause();
    durationInNanos += (ClockProvider.timeInNanos() - startInNanos);
  }
}