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 package com.android.emergency.edit;
17 
18 import android.app.Activity;
19 import android.app.DialogFragment;
20 import android.content.ActivityNotFoundException;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.net.Uri;
24 import android.os.Bundle;
25 import android.provider.ContactsContract;
26 import android.util.Log;
27 import android.widget.Toast;
28 
29 import androidx.preference.Preference;
30 import androidx.preference.Preference.OnPreferenceChangeListener;
31 import androidx.preference.PreferenceFragment;
32 import androidx.preference.PreferenceGroup;
33 
34 import com.android.emergency.PreferenceKeys;
35 import com.android.emergency.R;
36 import com.android.emergency.ReloadablePreferenceInterface;
37 import com.android.emergency.preferences.EmergencyContactsPreference;
38 import com.android.emergency.preferences.EmergencyNamePreference;
39 import com.android.emergency.util.PreferenceUtils;
40 import com.android.internal.annotations.VisibleForTesting;
41 import com.android.settingslib.CustomDialogPreference;
42 import com.android.settingslib.CustomEditTextPreference;
43 
44 import java.util.HashMap;
45 import java.util.Map;
46 
47 /** Fragment for editing emergency info, including medical info and emergency contacts. */
48 public class EditInfoFragment extends PreferenceFragment {
49     private static final String TAG = "EditInfoFragment";
50 
51     /** Result code for contact picker */
52     private static final int CONTACT_PICKER_RESULT = 1001;
53 
54     private static final String DIALOG_PREFERENCE_TAG = "dialog_preference";
55 
56     private final Map<String, Preference> mMedicalInfoPreferences =
57             new HashMap<>();
58 
59     /** The category that holds the emergency contacts. */
60     private EmergencyContactsPreference mEmergencyContactsPreferenceCategory;
61 
62     private EmergencyNamePreference mEmergencyNamePreference;
63 
64     @Override
onCreatePreferences(Bundle savedInstanceState, String rootKey)65     public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
66         setPreferencesFromResource(R.xml.edit_emergency_info, rootKey);
67 
68         for (String preferenceKey : PreferenceKeys.KEYS_EDIT_EMERGENCY_INFO) {
69             Preference preference = findPreference(preferenceKey);
70             mMedicalInfoPreferences.put(preferenceKey, preference);
71 
72             preference.setOnPreferenceChangeListener(new PreferenceChangeListener(getActivity()));
73 
74             if (((ReloadablePreferenceInterface) preference).isNotSet()) {
75                 getMedicalInfoParent().removePreference(preference);
76             }
77         }
78 
79         mEmergencyNamePreference = findPreference(PreferenceKeys.KEY_NAME);
80 
81         // Fill in emergency contacts.
82         mEmergencyContactsPreferenceCategory =
83                 findPreference(PreferenceKeys.KEY_EMERGENCY_CONTACTS);
84 
85         Preference addEmergencyContact = findPreference(PreferenceKeys.KEY_ADD_EMERGENCY_CONTACT);
86         addEmergencyContact.setOnPreferenceClickListener(preference -> {
87             // By using ContactsContract.CommonDataKinds.Phone.CONTENT_URI, the user is
88             // presented with a list of contacts, with one entry per phone number.
89             // The selected contact is guaranteed to have a name and phone number.
90             Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
91                     ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
92             try {
93                 startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
94                 return true;
95             } catch (ActivityNotFoundException e) {
96                 Log.w(TAG, "No contact app available to display the contacts", e);
97                 Toast.makeText(getContext(),
98                         getContext().getString(R.string.fail_load_contact_picker),
99                         Toast.LENGTH_LONG).show();
100                 return false;
101             }
102         });
103     }
104 
105     @Override
onResume()106     public void onResume() {
107         super.onResume();
108         reloadFromPreference();
109         mEmergencyNamePreference.reloadFromUserManager();
110     }
111 
112     /** Reloads the contacts by reading the value from the shared preferences. */
reloadFromPreference()113     public void reloadFromPreference() {
114         for (Preference preference : mMedicalInfoPreferences.values()) {
115             ReloadablePreferenceInterface reloadablePreference =
116                     (ReloadablePreferenceInterface) preference;
117             reloadablePreference.reloadFromPreference();
118             if (reloadablePreference.isNotSet()) {
119                 getMedicalInfoParent().removePreference(preference);
120             } else {
121                 // Note: this preference won't be added it if it already exists.
122                 getMedicalInfoParent().addPreference(preference);
123             }
124         }
125         mEmergencyContactsPreferenceCategory.reloadFromPreference();
126     }
127 
128     @Override
onDisplayPreferenceDialog(Preference preference)129     public void onDisplayPreferenceDialog(Preference preference) {
130         DialogFragment fragment = null;
131         if (preference instanceof CustomEditTextPreference) {
132             fragment = CustomEditTextPreference.CustomPreferenceDialogFragment
133                     .newInstance(preference.getKey());
134         } else if (preference instanceof CustomDialogPreference) {
135             fragment = EmergencyNamePreference.EmergencyNamePreferenceDialogFragment
136                     .newInstance(preference.getKey());
137         }
138         if (fragment != null) {
139             fragment.setTargetFragment(this, 0);
140             fragment.show(getFragmentManager(), DIALOG_PREFERENCE_TAG);
141         } else {
142             super.onDisplayPreferenceDialog(preference);
143         }
144     }
145 
146     @Override
onActivityResult(int requestCode, int resultCode, Intent data)147     public void onActivityResult(int requestCode, int resultCode, Intent data) {
148         if (requestCode == CONTACT_PICKER_RESULT && resultCode == Activity.RESULT_OK) {
149             Uri phoneUri = data.getData();
150             mEmergencyContactsPreferenceCategory.addNewEmergencyContact(phoneUri);
151         }
152     }
153 
154     @VisibleForTesting
getMedicalInfoParent()155     public PreferenceGroup getMedicalInfoParent() {
156         return findPreference(PreferenceKeys.KEY_MEDICAL_INFO);
157     }
158 
159     @VisibleForTesting
getMedicalInfoPreference(String key)160     public Preference getMedicalInfoPreference(String key) {
161         return mMedicalInfoPreferences.get(key);
162     }
163 
164     @VisibleForTesting
165     static class PreferenceChangeListener implements OnPreferenceChangeListener {
166         private final Context mContext;
167 
PreferenceChangeListener(Context context)168         public PreferenceChangeListener(Context context) {
169             mContext = context;
170         }
171 
172         @Override
onPreferenceChange(Preference preferenceItem, Object value)173         public boolean onPreferenceChange(Preference preferenceItem, Object value) {
174             // Enable or disable settings suggestion, as appropriate.
175             PreferenceUtils.updateSettingsSuggestionState(mContext);
176             // If the preference implements OnPreferenceChangeListener, notify it of the
177             // change as well.
178             if (Preference.OnPreferenceChangeListener.class.isInstance(preferenceItem)) {
179                 return ((Preference.OnPreferenceChangeListener) preferenceItem)
180                         .onPreferenceChange(preferenceItem, value);
181             }
182             return true;
183         }
184     }
185 }
186