SafeDismissDialogFragment.java revision 38fef3bf253578f518d1bc727da4afb263194398
1/* 2 * Copyright (C) 2015 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 17package com.android.tv.dialog; 18 19import android.app.Activity; 20import android.app.DialogFragment; 21import com.android.tv.MainActivity; 22import com.android.tv.TvApplication; 23import com.android.tv.analytics.HasTrackerLabel; 24import com.android.tv.analytics.Tracker; 25 26/** Provides the safe dismiss feature regardless of the DialogFragment's life cycle. */ 27public abstract class SafeDismissDialogFragment extends DialogFragment implements HasTrackerLabel { 28 private MainActivity mActivity; 29 private boolean mAttached = false; 30 private boolean mDismissPending = false; 31 private Tracker mTracker; 32 33 @Override 34 public void onAttach(Activity activity) { 35 super.onAttach(activity); 36 mAttached = true; 37 if (activity instanceof MainActivity) { 38 mActivity = (MainActivity) activity; 39 } 40 mTracker = TvApplication.getSingletons(activity).getTracker(); 41 if (mDismissPending) { 42 mDismissPending = false; 43 dismiss(); 44 } 45 } 46 47 @Override 48 public void onResume() { 49 super.onResume(); 50 mTracker.sendScreenView(getTrackerLabel()); 51 } 52 53 @Override 54 public void onDestroy() { 55 if (mActivity != null) { 56 mActivity.getOverlayManager().onDialogDestroyed(); 57 } 58 super.onDestroy(); 59 } 60 61 @Override 62 public void onDetach() { 63 super.onDetach(); 64 mAttached = false; 65 mTracker = null; 66 } 67 68 /** Dismiss safely regardless of the DialogFragment's life cycle. */ 69 @Override 70 public void dismiss() { 71 if (!mAttached) { 72 // dismiss() before getFragmentManager() is set cause NPE in dismissInternal(). 73 // FragmentManager is set when a fragment is used in a transaction, 74 // so wait here until we can dismiss safely. 75 mDismissPending = true; 76 } else { 77 super.dismiss(); 78 } 79 } 80} 81