1 /*
2  * Copyright (C) 2016 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 com.android.dialer.app.contactinfo;
18 
19 import android.os.Bundle;
20 import android.support.annotation.NonNull;
21 import android.support.v4.app.Fragment;
22 import android.support.v4.app.FragmentManager;
23 import android.support.v7.app.AppCompatActivity;
24 import com.android.dialer.phonenumbercache.ContactInfo;
25 import com.android.dialer.util.ExpirableCache;
26 
27 /**
28  * Fragment without any UI whose purpose is to retain an instance of {@link ExpirableCache} across
29  * configuration change through the use of {@link #setRetainInstance(boolean)}. This is done as
30  * opposed to implementing {@link android.os.Parcelable} as it is a less widespread change.
31  */
32 public class ExpirableCacheHeadlessFragment extends Fragment {
33 
34   private static final String FRAGMENT_TAG = "ExpirableCacheHeadlessFragment";
35   private static final int CONTACT_INFO_CACHE_SIZE = 100;
36 
37   private ExpirableCache<NumberWithCountryIso, ContactInfo> retainedCache;
38 
39   @NonNull
attach(@onNull AppCompatActivity parentActivity)40   public static ExpirableCacheHeadlessFragment attach(@NonNull AppCompatActivity parentActivity) {
41     return attach(parentActivity.getSupportFragmentManager());
42   }
43 
44   @NonNull
attach(FragmentManager fragmentManager)45   private static ExpirableCacheHeadlessFragment attach(FragmentManager fragmentManager) {
46     ExpirableCacheHeadlessFragment fragment =
47         (ExpirableCacheHeadlessFragment) fragmentManager.findFragmentByTag(FRAGMENT_TAG);
48     if (fragment == null) {
49       fragment = new ExpirableCacheHeadlessFragment();
50       // Allowing state loss since in rare cases this is called after activity's state is saved and
51       // it's fine if the cache is lost.
52       fragmentManager.beginTransaction().add(fragment, FRAGMENT_TAG).commitNowAllowingStateLoss();
53     }
54     return fragment;
55   }
56 
57   @Override
onCreate(Bundle savedInstanceState)58   public void onCreate(Bundle savedInstanceState) {
59     super.onCreate(savedInstanceState);
60     retainedCache = ExpirableCache.create(CONTACT_INFO_CACHE_SIZE);
61     setRetainInstance(true);
62   }
63 
getRetainedCache()64   public ExpirableCache<NumberWithCountryIso, ContactInfo> getRetainedCache() {
65     return retainedCache;
66   }
67 }
68