blob: 179517b1530ba0179ceb89ccde11434a66b82513 [file] [log] [blame]
Santos Cordon176ae282014-07-14 02:02:14 -07001/*
2 * Copyright (C) 2014 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
Tyler Gunn7cc70b42014-09-12 22:17:27 -070017package com.android.server.telecom;
Santos Cordon176ae282014-07-14 02:02:14 -070018
Tyler Gunncb59b672014-08-20 09:02:11 -070019import android.Manifest;
Evan Charlton105d9772014-11-25 14:08:53 -080020import android.content.ComponentName;
21import android.content.Context;
Evan Charltonaf51ceb2014-07-30 11:56:36 -070022import android.content.Intent;
23import android.content.pm.PackageManager;
24import android.content.pm.ResolveInfo;
Tyler Gunncb59b672014-08-20 09:02:11 -070025import android.content.pm.ServiceInfo;
Tony Mak4a3e2fd2015-12-04 11:58:38 +000026import android.content.pm.UserInfo;
Ihab Awadd9f54382014-10-24 11:44:47 -070027import android.graphics.Bitmap;
28import android.graphics.BitmapFactory;
Santos Cordon9c30c282015-05-13 16:28:27 -070029import android.graphics.drawable.Icon;
Evan Charlton105d9772014-11-25 14:08:53 -080030import android.net.Uri;
Tyler Gunn369c8742015-10-07 15:39:28 -070031import android.os.Bundle;
Hall Liu3f7f64d2016-01-07 17:40:13 -080032import android.os.AsyncTask;
Sailesh Nepalaecfa9b2015-06-16 14:55:27 -070033import android.os.PersistableBundle;
Evan Charlton105d9772014-11-25 14:08:53 -080034import android.os.Process;
35import android.os.UserHandle;
36import android.os.UserManager;
Tyler Gunn84253572014-09-02 14:50:05 -070037import android.provider.Settings;
Christine Hallstromffe558c2016-11-30 16:05:13 -080038import android.telecom.CallAudioState;
Tyler Gunn7cc70b42014-09-12 22:17:27 -070039import android.telecom.ConnectionService;
Santos Cordon59c21a72015-06-11 10:11:21 -070040import android.telecom.DefaultDialerManager;
Brad Ebinger953e1af2016-10-05 15:45:22 -070041import android.telecom.Log;
Tyler Gunn7cc70b42014-09-12 22:17:27 -070042import android.telecom.PhoneAccount;
43import android.telecom.PhoneAccountHandle;
Sailesh Nepalaecfa9b2015-06-16 14:55:27 -070044import android.telephony.CarrierConfigManager;
Nancy Chen140004a2014-10-15 15:48:38 -070045import android.telephony.PhoneNumberUtils;
Nancy Chen5a36b6e2014-10-23 17:42:42 -070046import android.telephony.SubscriptionManager;
Santos Cordon479b3022015-02-06 04:27:15 -080047import android.telephony.TelephonyManager;
Evan Charltonaf51ceb2014-07-30 11:56:36 -070048import android.text.TextUtils;
Ihab Awadb78b2762014-07-25 15:16:23 -070049import android.util.AtomicFile;
Ihab Awadd9f54382014-10-24 11:44:47 -070050import android.util.Base64;
Ihab Awadb78b2762014-07-25 15:16:23 -070051import android.util.Xml;
Santos Cordon176ae282014-07-14 02:02:14 -070052
Tyler Gunn91d43cf2014-09-17 12:19:39 -070053// TODO: Needed for move to system service: import com.android.internal.R;
Sailesh Nepal0e1dc5a2014-07-30 11:08:54 -070054import com.android.internal.annotations.VisibleForTesting;
55import com.android.internal.util.FastXmlSerializer;
Tyler Gunn9787e0e2014-10-14 14:36:12 -070056import com.android.internal.util.IndentingPrintWriter;
Sailesh Nepal0e1dc5a2014-07-30 11:08:54 -070057import com.android.internal.util.XmlUtils;
58
Evan Charltonaf51ceb2014-07-30 11:56:36 -070059import org.xmlpull.v1.XmlPullParser;
60import org.xmlpull.v1.XmlPullParserException;
61import org.xmlpull.v1.XmlSerializer;
62
Ihab Awadb78b2762014-07-25 15:16:23 -070063import java.io.BufferedInputStream;
Santos Cordon9c30c282015-05-13 16:28:27 -070064import java.io.ByteArrayInputStream;
Ihab Awadd9f54382014-10-24 11:44:47 -070065import java.io.ByteArrayOutputStream;
Ihab Awadb78b2762014-07-25 15:16:23 -070066import java.io.File;
67import java.io.FileNotFoundException;
68import java.io.FileOutputStream;
69import java.io.IOException;
70import java.io.InputStream;
Tyler Gunn84253572014-09-02 14:50:05 -070071import java.lang.Integer;
Tyler Gunncb59b672014-08-20 09:02:11 -070072import java.lang.SecurityException;
Tyler Gunnd900ce62014-08-13 11:40:59 -070073import java.lang.String;
Santos Cordon176ae282014-07-14 02:02:14 -070074import java.util.ArrayList;
Sailesh Nepal91fc8092015-02-14 15:44:55 -080075import java.util.Collections;
Srikanth Chintalad5d2dd92016-06-23 16:02:33 +053076import java.util.Comparator;
Tyler Gunnd900ce62014-08-13 11:40:59 -070077import java.util.Iterator;
Santos Cordon176ae282014-07-14 02:02:14 -070078import java.util.List;
Tony Mak4a3e2fd2015-12-04 11:58:38 +000079import java.util.Map;
Santos Cordon176ae282014-07-14 02:02:14 -070080import java.util.Objects;
Brad Ebinger0c87b3c2016-06-10 17:23:02 -070081import java.util.Optional;
Tony Mak4a3e2fd2015-12-04 11:58:38 +000082import java.util.concurrent.ConcurrentHashMap;
Ihab Awadb78b2762014-07-25 15:16:23 -070083import java.util.concurrent.CopyOnWriteArrayList;
Brad Ebinger0c87b3c2016-06-10 17:23:02 -070084import java.util.stream.Collector;
85import java.util.stream.Collectors;
86import java.util.stream.Stream;
Santos Cordon176ae282014-07-14 02:02:14 -070087
88/**
Evan Charlton89176372014-07-19 18:23:09 -070089 * Handles writing and reading PhoneAccountHandle registration entries. This is a simple verbatim
Santos Cordon6a212642015-05-08 16:35:23 -070090 * delegate for all the account handling methods on {@link android.telecom.TelecomManager} as
91 * implemented in {@link TelecomServiceImpl}, with the notable exception that
92 * {@link TelecomServiceImpl} is responsible for security checking to make sure that the caller has
93 * proper authority over the {@code ComponentName}s they are declaring in their
94 * {@code PhoneAccountHandle}s.
95 *
96 *
97 * -- About Users and Phone Accounts --
98 *
Santos Cordon9c30c282015-05-13 16:28:27 -070099 * We store all phone accounts for all users in a single place, which means that there are three
100 * users that we have to deal with in code:
Santos Cordon6a212642015-05-08 16:35:23 -0700101 * 1) The Android User that is currently active on the device.
102 * 2) The user which owns/registers the phone account.
103 * 3) The user running the app that is requesting the phone account information.
104 *
105 * For example, I have a device with 2 users, primary (A) and secondary (B), and the secondary user
Tony Mak240656f2015-12-04 11:36:22 +0000106 * has a work profile running as another user (B2). Each user/profile only have the visibility of
107 * phone accounts owned by them. Lets say, user B (settings) is requesting a list of phone accounts,
108 * and the list only contains phone accounts owned by user B and accounts with
109 * {@link PhoneAccount#CAPABILITY_MULTI_USER}.
Santos Cordon6a212642015-05-08 16:35:23 -0700110 *
111 * In practice, (2) is stored with the phone account handle and is part of the handle's ID. (1) is
112 * saved in {@link #mCurrentUserHandle} and (3) we get from Binder.getCallingUser(). We check these
113 * users for visibility before returning any phone accounts.
Santos Cordon176ae282014-07-14 02:02:14 -0700114 */
Brad Ebinger53855132015-10-30 10:58:19 -0700115public class PhoneAccountRegistrar {
Santos Cordon176ae282014-07-14 02:02:14 -0700116
Yorke Lee5e8836a2014-08-22 15:25:18 -0700117 public static final PhoneAccountHandle NO_ACCOUNT_SELECTED =
118 new PhoneAccountHandle(new ComponentName("null", "null"), "NO_ACCOUNT_SELECTED");
119
Ihab Awadb78b2762014-07-25 15:16:23 -0700120 public abstract static class Listener {
121 public void onAccountsChanged(PhoneAccountRegistrar registrar) {}
122 public void onDefaultOutgoingChanged(PhoneAccountRegistrar registrar) {}
123 public void onSimCallManagerChanged(PhoneAccountRegistrar registrar) {}
Tyler Gunnea4c6fb2017-04-14 13:46:21 -0700124 public void onPhoneAccountRegistered(PhoneAccountRegistrar registrar,
125 PhoneAccountHandle handle) {}
126 public void onPhoneAccountUnRegistered(PhoneAccountRegistrar registrar,
127 PhoneAccountHandle handle) {}
Ihab Awadb78b2762014-07-25 15:16:23 -0700128 }
129
Tyler Gunn2b17f232017-03-08 08:51:00 -0800130 /**
131 * Abstracts away dependency on the {@link PackageManager} required to fetch the label for an
132 * app.
133 */
134 public interface AppLabelProxy {
135 CharSequence getAppLabel(String packageName);
136 }
137
Ihab Awadb78b2762014-07-25 15:16:23 -0700138 private static final String FILE_NAME = "phone-account-registrar-state.xml";
Tyler Gunn84253572014-09-02 14:50:05 -0700139 @VisibleForTesting
Tony Mak4a3e2fd2015-12-04 11:58:38 +0000140 public static final int EXPECTED_STATE_VERSION = 9;
Tyler Gunn84253572014-09-02 14:50:05 -0700141
142 /** Keep in sync with the same in SipSettings.java */
143 private static final String SIP_SHARED_PREFERENCES = "SIP_PREFERENCES";
Ihab Awadb78b2762014-07-25 15:16:23 -0700144
145 private final List<Listener> mListeners = new CopyOnWriteArrayList<>();
146 private final AtomicFile mAtomicFile;
Santos Cordonafe59e52014-08-22 16:48:43 -0700147 private final Context mContext;
Evan Charlton105d9772014-11-25 14:08:53 -0800148 private final UserManager mUserManager;
Wink Saville33c05d32014-11-20 13:04:17 -0800149 private final SubscriptionManager mSubscriptionManager;
Hall Liu2b33df72016-12-06 18:15:39 -0800150 private final DefaultDialerCache mDefaultDialerCache;
Tyler Gunn2b17f232017-03-08 08:51:00 -0800151 private final AppLabelProxy mAppLabelProxy;
Ihab Awadb78b2762014-07-25 15:16:23 -0700152 private State mState;
Evan Charlton105d9772014-11-25 14:08:53 -0800153 private UserHandle mCurrentUserHandle;
Hall Liu3f7f64d2016-01-07 17:40:13 -0800154 private interface PhoneAccountRegistrarWriteLock {}
155 private final PhoneAccountRegistrarWriteLock mWriteLock =
156 new PhoneAccountRegistrarWriteLock() {};
Santos Cordon176ae282014-07-14 02:02:14 -0700157
Nancy Chen06ce0622014-10-23 01:17:35 +0000158 @VisibleForTesting
Tyler Gunn2b17f232017-03-08 08:51:00 -0800159 public PhoneAccountRegistrar(Context context, DefaultDialerCache defaultDialerCache,
160 AppLabelProxy appLabelProxy) {
161 this(context, FILE_NAME, defaultDialerCache, appLabelProxy);
Ihab Awadb78b2762014-07-25 15:16:23 -0700162 }
163
164 @VisibleForTesting
Hall Liu2b33df72016-12-06 18:15:39 -0800165 public PhoneAccountRegistrar(Context context, String fileName,
Tyler Gunn2b17f232017-03-08 08:51:00 -0800166 DefaultDialerCache defaultDialerCache, AppLabelProxy appLabelProxy) {
167
Ihab Awadb78b2762014-07-25 15:16:23 -0700168 mAtomicFile = new AtomicFile(new File(context.getFilesDir(), fileName));
Tyler Gunn91d43cf2014-09-17 12:19:39 -0700169
Ihab Awadb78b2762014-07-25 15:16:23 -0700170 mState = new State();
Santos Cordonafe59e52014-08-22 16:48:43 -0700171 mContext = context;
Evan Charlton105d9772014-11-25 14:08:53 -0800172 mUserManager = UserManager.get(context);
Hall Liu2b33df72016-12-06 18:15:39 -0800173 mDefaultDialerCache = defaultDialerCache;
Wink Saville33c05d32014-11-20 13:04:17 -0800174 mSubscriptionManager = SubscriptionManager.from(mContext);
Tyler Gunn2b17f232017-03-08 08:51:00 -0800175 mAppLabelProxy = appLabelProxy;
Evan Charlton105d9772014-11-25 14:08:53 -0800176 mCurrentUserHandle = Process.myUserHandle();
Ihab Awadb78b2762014-07-25 15:16:23 -0700177 read();
Santos Cordon176ae282014-07-14 02:02:14 -0700178 }
179
Tyler Gunn84253572014-09-02 14:50:05 -0700180 /**
Nancy Chen140004a2014-10-15 15:48:38 -0700181 * Retrieves the subscription id for a given phone account if it exists. Subscription ids
182 * apply only to PSTN/SIM card phone accounts so all other accounts should not have a
183 * subscription id.
184 * @param accountHandle The handle for the phone account for which to retrieve the
185 * subscription id.
Wink Saville35850602014-10-23 15:57:21 -0700186 * @return The value of the subscription id or -1 if it does not exist or is not valid.
Nancy Chen140004a2014-10-15 15:48:38 -0700187 */
Wink Saville35850602014-10-23 15:57:21 -0700188 public int getSubscriptionIdForPhoneAccount(PhoneAccountHandle accountHandle) {
Tony Mak240656f2015-12-04 11:36:22 +0000189 PhoneAccount account = getPhoneAccountUnchecked(accountHandle);
Santos Cordon479b3022015-02-06 04:27:15 -0800190
Santos Cordon6a212642015-05-08 16:35:23 -0700191 if (account != null && account.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
Santos Cordon479b3022015-02-06 04:27:15 -0800192 TelephonyManager tm =
193 (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
194 return tm.getSubIdForPhoneAccount(account);
Nancy Chen140004a2014-10-15 15:48:38 -0700195 }
Santos Cordon479b3022015-02-06 04:27:15 -0800196 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
Nancy Chen140004a2014-10-15 15:48:38 -0700197 }
198
199 /**
Evan Charlton105d9772014-11-25 14:08:53 -0800200 * Retrieves the default outgoing phone account supporting the specified uriScheme. Note that if
201 * {@link #mCurrentUserHandle} does not have visibility into the current default, {@code null}
202 * will be returned.
203 *
Tyler Gunn84253572014-09-02 14:50:05 -0700204 * @param uriScheme The URI scheme for the outgoing call.
205 * @return The {@link PhoneAccountHandle} to use.
206 */
Tony Mak240656f2015-12-04 11:36:22 +0000207 public PhoneAccountHandle getOutgoingPhoneAccountForScheme(String uriScheme,
208 UserHandle userHandle) {
209 final PhoneAccountHandle userSelected = getUserSelectedOutgoingPhoneAccount(userHandle);
Tyler Gunn84253572014-09-02 14:50:05 -0700210
Yorke Lee5e8836a2014-08-22 15:25:18 -0700211 if (userSelected != null) {
Tyler Gunn84253572014-09-02 14:50:05 -0700212 // If there is a default PhoneAccount, ensure it supports calls to handles with the
213 // specified uriScheme.
Tony Mak240656f2015-12-04 11:36:22 +0000214 final PhoneAccount userSelectedAccount = getPhoneAccountUnchecked(userSelected);
Santos Cordon6a212642015-05-08 16:35:23 -0700215 if (userSelectedAccount.supportsUriScheme(uriScheme)) {
Tyler Gunn84253572014-09-02 14:50:05 -0700216 return userSelected;
217 }
Ihab Awad293edf22014-07-24 17:52:29 -0700218 }
219
Tony Mak240656f2015-12-04 11:36:22 +0000220 List<PhoneAccountHandle> outgoing = getCallCapablePhoneAccounts(uriScheme, false,
221 userHandle);
Ihab Awad6fb37c82014-08-07 19:48:57 -0700222 switch (outgoing.size()) {
Ihab Awad293edf22014-07-24 17:52:29 -0700223 case 0:
224 // There are no accounts, so there can be no default
225 return null;
226 case 1:
Evan Charlton105d9772014-11-25 14:08:53 -0800227 // There is only one account, which is by definition the default.
Santos Cordon6a212642015-05-08 16:35:23 -0700228 return outgoing.get(0);
Ihab Awad293edf22014-07-24 17:52:29 -0700229 default:
230 // There are multiple accounts with no selected default
231 return null;
Ihab Awadf2a84912014-07-22 21:09:25 -0700232 }
Ihab Awad104f8062014-07-17 11:29:35 -0700233 }
Santos Cordon176ae282014-07-14 02:02:14 -0700234
Tony Mak240656f2015-12-04 11:36:22 +0000235 public PhoneAccountHandle getOutgoingPhoneAccountForSchemeOfCurrentUser(String uriScheme) {
236 return getOutgoingPhoneAccountForScheme(uriScheme, mCurrentUserHandle);
237 }
238
Evan Charlton105d9772014-11-25 14:08:53 -0800239 /**
240 * @return The user-selected outgoing {@link PhoneAccount}, or null if it hasn't been set (or
241 * if it was set by another user).
242 */
Hall Liuecda5542015-12-04 11:31:31 -0800243 @VisibleForTesting
244 public PhoneAccountHandle getUserSelectedOutgoingPhoneAccount(UserHandle userHandle) {
Tony Mak4a3e2fd2015-12-04 11:58:38 +0000245 if (userHandle == null) {
246 return null;
247 }
248 DefaultPhoneAccountHandle defaultPhoneAccountHandle = mState.defaultOutgoingAccountHandles
249 .get(userHandle);
250 if (defaultPhoneAccountHandle == null) {
251 return null;
252 }
253 // Make sure the account is still registered and owned by the user.
254 PhoneAccount account = getPhoneAccount(defaultPhoneAccountHandle.phoneAccountHandle,
255 userHandle);
Hall Liuecda5542015-12-04 11:31:31 -0800256
Santos Cordon6a212642015-05-08 16:35:23 -0700257 if (account != null) {
Tony Mak4a3e2fd2015-12-04 11:58:38 +0000258 return defaultPhoneAccountHandle.phoneAccountHandle;
Yorke Lee5e8836a2014-08-22 15:25:18 -0700259 }
260 return null;
261 }
262
Santos Cordon6a212642015-05-08 16:35:23 -0700263 /**
Brad Ebinger0c87b3c2016-06-10 17:23:02 -0700264 * @return The {@link DefaultPhoneAccountHandle} containing the user-selected default calling
265 * account and group Id for the {@link UserHandle} specified.
266 */
267 private DefaultPhoneAccountHandle getUserSelectedDefaultPhoneAccount(UserHandle userHandle) {
268 if (userHandle == null) {
269 return null;
270 }
271 DefaultPhoneAccountHandle defaultPhoneAccountHandle = mState.defaultOutgoingAccountHandles
272 .get(userHandle);
273 if (defaultPhoneAccountHandle == null) {
274 return null;
275 }
276
277 return defaultPhoneAccountHandle;
278 }
279
280 /**
281 * @return The currently registered PhoneAccount in Telecom that has the same group Id.
282 */
283 private PhoneAccount getPhoneAccountByGroupId(String groupId, ComponentName groupComponentName,
284 UserHandle userHandle, PhoneAccountHandle excludePhoneAccountHandle) {
285 if (groupId == null || groupId.isEmpty() || userHandle == null) {
286 return null;
287 }
288 // Get the PhoneAccount with the same group Id (and same ComponentName) that is not the
289 // newAccount that was just added
290 List<PhoneAccount> accounts = getAllPhoneAccounts(userHandle).stream()
291 .filter(account -> groupId.equals(account.getGroupId()) &&
292 !account.getAccountHandle().equals(excludePhoneAccountHandle) &&
293 Objects.equals(account.getAccountHandle().getComponentName(),
294 groupComponentName))
295 .collect(Collectors.toList());
296 // There should be one or no PhoneAccounts with the same group Id
297 if (accounts.size() > 1) {
298 Log.w(this, "Found multiple PhoneAccounts registered to the same Group Id!");
299 }
300 return accounts.isEmpty() ? null : accounts.get(0);
301 }
302
303 /**
Santos Cordon6a212642015-05-08 16:35:23 -0700304 * Sets the phone account with which to place all calls by default. Set by the user
305 * within phone settings.
306 */
Tony Mak4a3e2fd2015-12-04 11:58:38 +0000307 public void setUserSelectedOutgoingPhoneAccount(PhoneAccountHandle accountHandle,
308 UserHandle userHandle) {
309 if (userHandle == null) {
310 return;
311 }
Evan Charlton89176372014-07-19 18:23:09 -0700312 if (accountHandle == null) {
Ihab Awad104f8062014-07-17 11:29:35 -0700313 // Asking to clear the default outgoing is a valid request
Tony Mak4a3e2fd2015-12-04 11:58:38 +0000314 mState.defaultOutgoingAccountHandles.remove(userHandle);
Ihab Awad104f8062014-07-17 11:29:35 -0700315 } else {
Tony Mak4a3e2fd2015-12-04 11:58:38 +0000316 PhoneAccount account = getPhoneAccount(accountHandle, userHandle);
Santos Cordon6a212642015-05-08 16:35:23 -0700317 if (account == null) {
Ihab Awadb78b2762014-07-25 15:16:23 -0700318 Log.w(this, "Trying to set nonexistent default outgoing %s",
319 accountHandle);
320 return;
321 }
322
Santos Cordon6a212642015-05-08 16:35:23 -0700323 if (!account.hasCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)) {
Ihab Awadb78b2762014-07-25 15:16:23 -0700324 Log.w(this, "Trying to set non-call-provider default outgoing %s",
Evan Charlton89176372014-07-19 18:23:09 -0700325 accountHandle);
Ihab Awad104f8062014-07-17 11:29:35 -0700326 return;
327 }
328
Santos Cordon6a212642015-05-08 16:35:23 -0700329 if (account.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
Nancy Chen5a36b6e2014-10-23 17:42:42 -0700330 // If the account selected is a SIM account, propagate down to the subscription
331 // record.
Wink Saville7ce6e782014-10-27 10:56:46 -0700332 int subId = getSubscriptionIdForPhoneAccount(accountHandle);
Wink Saville33c05d32014-11-20 13:04:17 -0800333 mSubscriptionManager.setDefaultVoiceSubId(subId);
Nancy Chen5a36b6e2014-10-23 17:42:42 -0700334 }
335
Tony Mak4a3e2fd2015-12-04 11:58:38 +0000336 mState.defaultOutgoingAccountHandles
Brad Ebinger0c87b3c2016-06-10 17:23:02 -0700337 .put(userHandle, new DefaultPhoneAccountHandle(userHandle, accountHandle,
338 account.getGroupId()));
Santos Cordon176ae282014-07-14 02:02:14 -0700339 }
340
Ihab Awad293edf22014-07-24 17:52:29 -0700341 write();
Ihab Awadb78b2762014-07-25 15:16:23 -0700342 fireDefaultOutgoingChanged();
Santos Cordon176ae282014-07-14 02:02:14 -0700343 }
344
Nancy Chen668dee02014-11-19 15:31:31 -0800345 boolean isUserSelectedSmsPhoneAccount(PhoneAccountHandle accountHandle) {
Shishir Agrawalce688742016-01-25 15:02:21 -0800346 return getSubscriptionIdForPhoneAccount(accountHandle) ==
347 SubscriptionManager.getDefaultSmsSubscriptionId();
Sailesh Nepalfc43ea82015-07-28 19:30:28 -0700348 }
349
Sailesh Nepal8ed7eeb2015-09-08 12:30:13 -0700350 public ComponentName getSystemSimCallManagerComponent() {
351 String defaultSimCallManager = null;
352 CarrierConfigManager configManager = (CarrierConfigManager) mContext.getSystemService(
353 Context.CARRIER_CONFIG_SERVICE);
354 PersistableBundle configBundle = configManager.getConfig();
355 if (configBundle != null) {
356 defaultSimCallManager = configBundle.getString(
357 CarrierConfigManager.KEY_DEFAULT_SIM_CALL_MANAGER_STRING);
358 }
359 return TextUtils.isEmpty(defaultSimCallManager)
360 ? null : ComponentName.unflattenFromString(defaultSimCallManager);
361 }
362
Tony Mak240656f2015-12-04 11:36:22 +0000363 public PhoneAccountHandle getSimCallManagerOfCurrentUser() {
364 return getSimCallManager(mCurrentUserHandle);
365 }
366
Sailesh Nepalfc43ea82015-07-28 19:30:28 -0700367 /**
368 * Returns the {@link PhoneAccountHandle} corresponding to the currently active SIM Call
369 * Manager. SIM Call Manager returned corresponds to the following priority order:
370 * 1. If a SIM Call Manager {@link PhoneAccount} is registered for the same package as the
371 * default dialer, then that one is returned.
372 * 2. If there is a SIM Call Manager {@link PhoneAccount} registered which matches the
373 * carrier configuration's default, then that one is returned.
374 * 3. Otherwise, we return null.
375 */
Tony Mak240656f2015-12-04 11:36:22 +0000376 public PhoneAccountHandle getSimCallManager(UserHandle userHandle) {
Santos Cordon59c21a72015-06-11 10:11:21 -0700377 // Get the default dialer in case it has a connection manager associated with it.
Hall Liu2b33df72016-12-06 18:15:39 -0800378 String dialerPackage = mDefaultDialerCache
379 .getDefaultDialerApplication(userHandle.getIdentifier());
Evan Charltonaf51ceb2014-07-30 11:56:36 -0700380
Sailesh Nepalaecfa9b2015-06-16 14:55:27 -0700381 // Check carrier config.
Sailesh Nepal8ed7eeb2015-09-08 12:30:13 -0700382 ComponentName systemSimCallManagerComponent = getSystemSimCallManagerComponent();
Sailesh Nepal91fc8092015-02-14 15:44:55 -0800383
Santos Cordon59c21a72015-06-11 10:11:21 -0700384 PhoneAccountHandle dialerSimCallManager = null;
385 PhoneAccountHandle systemSimCallManager = null;
Sailesh Nepal91fc8092015-02-14 15:44:55 -0800386
Santos Cordon59c21a72015-06-11 10:11:21 -0700387 if (!TextUtils.isEmpty(dialerPackage) || systemSimCallManagerComponent != null) {
388 // loop through and look for any connection manager in the same package.
389 List<PhoneAccountHandle> allSimCallManagers = getPhoneAccountHandles(
390 PhoneAccount.CAPABILITY_CONNECTION_MANAGER, null, null,
Tony Mak240656f2015-12-04 11:36:22 +0000391 true /* includeDisabledAccounts */, userHandle);
Santos Cordon59c21a72015-06-11 10:11:21 -0700392 for (PhoneAccountHandle accountHandle : allSimCallManagers) {
393 ComponentName component = accountHandle.getComponentName();
394
395 // Store the system connection manager if found
396 if (systemSimCallManager == null
397 && Objects.equals(component, systemSimCallManagerComponent)
398 && !resolveComponent(accountHandle).isEmpty()) {
399 systemSimCallManager = accountHandle;
400
401 // Store the dialer connection manager if found
402 } else if (dialerSimCallManager == null
403 && Objects.equals(component.getPackageName(), dialerPackage)
404 && !resolveComponent(accountHandle).isEmpty()) {
405 dialerSimCallManager = accountHandle;
Evan Charltonaf51ceb2014-07-30 11:56:36 -0700406 }
Evan Charltonaf51ceb2014-07-30 11:56:36 -0700407 }
Evan Charltonaf51ceb2014-07-30 11:56:36 -0700408 }
409
Santos Cordon59c21a72015-06-11 10:11:21 -0700410 PhoneAccountHandle retval = dialerSimCallManager != null ?
411 dialerSimCallManager : systemSimCallManager;
412
413 Log.i(this, "SimCallManager queried, returning: %s", retval);
414
Sailesh Nepalb3ccd7e2015-06-26 18:16:18 -0700415 return retval;
Ihab Awad293edf22014-07-24 17:52:29 -0700416 }
417
Evan Charlton105d9772014-11-25 14:08:53 -0800418 /**
Tony Mak240656f2015-12-04 11:36:22 +0000419 * If it is a outgoing call, sim call manager of call-initiating user is returned.
420 * Otherwise, we return the sim call manager of the user associated with the
421 * target phone account.
422 * @return phone account handle of sim call manager based on the ongoing call.
423 */
424 public PhoneAccountHandle getSimCallManagerFromCall(Call call) {
425 if (call == null) {
426 return null;
427 }
428 UserHandle userHandle = call.getInitiatingUser();
429 if (userHandle == null) {
430 userHandle = call.getTargetPhoneAccount().getUserHandle();
431 }
432 return getSimCallManager(userHandle);
433 }
434
435 /**
Evan Charlton105d9772014-11-25 14:08:53 -0800436 * Update the current UserHandle to track when users are switched. This will allow the
437 * PhoneAccountRegistar to self-filter the PhoneAccounts to make sure we don't leak anything
438 * across users.
Santos Cordon6a212642015-05-08 16:35:23 -0700439 * We cannot simply check the calling user because that would always return the primary user for
440 * all invocations originating with the system process.
Evan Charlton105d9772014-11-25 14:08:53 -0800441 *
442 * @param userHandle The {@link UserHandle}, as delivered by
443 * {@link Intent#ACTION_USER_SWITCHED}.
444 */
445 public void setCurrentUserHandle(UserHandle userHandle) {
446 if (userHandle == null) {
447 Log.d(this, "setCurrentUserHandle, userHandle = null");
448 userHandle = Process.myUserHandle();
449 }
450 Log.d(this, "setCurrentUserHandle, %s", userHandle);
451 mCurrentUserHandle = userHandle;
452 }
453
Yorke Lee71734c22015-06-02 14:22:56 -0700454 /**
455 * @return {@code true} if the phone account was successfully enabled/disabled, {@code false}
456 * otherwise.
457 */
458 public boolean enablePhoneAccount(PhoneAccountHandle accountHandle, boolean isEnabled) {
Tony Mak98e6bdc2015-11-25 21:54:05 +0000459 PhoneAccount account = getPhoneAccountUnchecked(accountHandle);
Hall Liu518a7dd2017-01-26 14:20:04 -0800460 Log.i(this, "Phone account %s %s.", accountHandle, isEnabled ? "enabled" : "disabled");
Santos Cordon638f05c2015-05-19 17:12:33 -0700461 if (account == null) {
462 Log.w(this, "Could not find account to enable: " + accountHandle);
Yorke Lee71734c22015-06-02 14:22:56 -0700463 return false;
Santos Cordon638f05c2015-05-19 17:12:33 -0700464 } else if (account.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
Santos Cordonea5cb932015-05-07 16:28:38 -0700465 // We never change the enabled state of SIM-based accounts.
Santos Cordon638f05c2015-05-19 17:12:33 -0700466 Log.w(this, "Could not change enable state of SIM account: " + accountHandle);
Yorke Lee71734c22015-06-02 14:22:56 -0700467 return false;
Santos Cordonea5cb932015-05-07 16:28:38 -0700468 }
469
Santos Cordon638f05c2015-05-19 17:12:33 -0700470 if (account.isEnabled() != isEnabled) {
Santos Cordonea5cb932015-05-07 16:28:38 -0700471 account.setIsEnabled(isEnabled);
Tony Mak48367162016-01-15 22:58:18 +0000472 if (!isEnabled) {
473 // If the disabled account is the default, remove it.
474 removeDefaultPhoneAccountHandle(accountHandle);
475 }
Santos Cordonea5cb932015-05-07 16:28:38 -0700476 write();
477 fireAccountsChanged();
478 }
Yorke Lee71734c22015-06-02 14:22:56 -0700479 return true;
Santos Cordonea5cb932015-05-07 16:28:38 -0700480 }
481
Tony Mak48367162016-01-15 22:58:18 +0000482 private void removeDefaultPhoneAccountHandle(PhoneAccountHandle phoneAccountHandle) {
483 Iterator<Map.Entry<UserHandle, DefaultPhoneAccountHandle>> iterator =
484 mState.defaultOutgoingAccountHandles.entrySet().iterator();
485 while (iterator.hasNext()) {
486 Map.Entry<UserHandle, DefaultPhoneAccountHandle> entry = iterator.next();
487 if (phoneAccountHandle.equals(entry.getValue().phoneAccountHandle)) {
488 iterator.remove();
489 }
490 }
491 }
492
Tony Mak240656f2015-12-04 11:36:22 +0000493 private boolean isVisibleForUser(PhoneAccount account, UserHandle userHandle,
494 boolean acrossProfiles) {
Evan Charlton105d9772014-11-25 14:08:53 -0800495 if (account == null) {
496 return false;
497 }
498
Tony Mak240656f2015-12-04 11:36:22 +0000499 if (userHandle == null) {
500 Log.w(this, "userHandle is null in isVisibleForUser");
501 return false;
502 }
503
Evan Charlton105d9772014-11-25 14:08:53 -0800504 // If this PhoneAccount has CAPABILITY_MULTI_USER, it should be visible to all users and
505 // all profiles. Only Telephony and SIP accounts should have this capability.
506 if (account.hasCapabilities(PhoneAccount.CAPABILITY_MULTI_USER)) {
507 return true;
508 }
509
510 UserHandle phoneAccountUserHandle = account.getAccountHandle().getUserHandle();
511 if (phoneAccountUserHandle == null) {
512 return false;
513 }
514
515 if (mCurrentUserHandle == null) {
Tony Mak240656f2015-12-04 11:36:22 +0000516 // In case we need to have emergency phone calls from the lock screen.
Evan Charlton105d9772014-11-25 14:08:53 -0800517 Log.d(this, "Current user is null; assuming true");
518 return true;
519 }
520
Tony Mak240656f2015-12-04 11:36:22 +0000521 if (acrossProfiles) {
522 return UserManager.get(mContext).isSameProfileGroup(userHandle.getIdentifier(),
523 phoneAccountUserHandle.getIdentifier());
524 } else {
525 return phoneAccountUserHandle.equals(userHandle);
Sailesh Nepal91fc8092015-02-14 15:44:55 -0800526 }
Evan Charlton105d9772014-11-25 14:08:53 -0800527 }
528
529 private List<ResolveInfo> resolveComponent(PhoneAccountHandle phoneAccountHandle) {
530 return resolveComponent(phoneAccountHandle.getComponentName(),
Tony Mak240656f2015-12-04 11:36:22 +0000531 phoneAccountHandle.getUserHandle());
Evan Charlton105d9772014-11-25 14:08:53 -0800532 }
533
534 private List<ResolveInfo> resolveComponent(ComponentName componentName,
535 UserHandle userHandle) {
mike dooley10a58312014-11-06 13:46:19 -0800536 PackageManager pm = mContext.getPackageManager();
537 Intent intent = new Intent(ConnectionService.SERVICE_INTERFACE);
538 intent.setComponent(componentName);
Sailesh Nepal91fc8092015-02-14 15:44:55 -0800539 try {
540 if (userHandle != null) {
541 return pm.queryIntentServicesAsUser(intent, 0, userHandle.getIdentifier());
542 } else {
543 return pm.queryIntentServices(intent, 0);
544 }
545 } catch (SecurityException e) {
Santos Cordon3188b362015-05-22 13:01:10 -0700546 Log.e(this, e, "%s is not visible for the calling user", componentName);
Sailesh Nepal91fc8092015-02-14 15:44:55 -0800547 return Collections.EMPTY_LIST;
Evan Charlton105d9772014-11-25 14:08:53 -0800548 }
mike dooley10a58312014-11-06 13:46:19 -0800549 }
550
Tyler Gunn8e0fef42014-09-08 18:34:44 -0700551 /**
552 * Retrieves a list of all {@link PhoneAccountHandle}s registered.
Santos Cordonea5cb932015-05-07 16:28:38 -0700553 * Only returns accounts which are enabled.
Tyler Gunn8e0fef42014-09-08 18:34:44 -0700554 *
555 * @return The list of {@link PhoneAccountHandle}s.
556 */
Tony Mak240656f2015-12-04 11:36:22 +0000557 public List<PhoneAccountHandle> getAllPhoneAccountHandles(UserHandle userHandle) {
558 return getPhoneAccountHandles(0, null, null, false, userHandle);
Ihab Awad293edf22014-07-24 17:52:29 -0700559 }
560
Tony Mak240656f2015-12-04 11:36:22 +0000561 public List<PhoneAccount> getAllPhoneAccounts(UserHandle userHandle) {
562 return getPhoneAccounts(0, null, null, false, userHandle);
563 }
564
565 public List<PhoneAccount> getAllPhoneAccountsOfCurrentUser() {
566 return getAllPhoneAccounts(mCurrentUserHandle);
Santos Cordonafe59e52014-08-22 16:48:43 -0700567 }
568
Tyler Gunn8e0fef42014-09-08 18:34:44 -0700569 /**
Nancy Chen309198e2014-09-15 18:02:49 -0700570 * Retrieves a list of all phone account call provider phone accounts supporting the
Tyler Gunn8e0fef42014-09-08 18:34:44 -0700571 * specified URI scheme.
572 *
573 * @param uriScheme The URI scheme.
574 * @return The phone account handles.
575 */
Santos Cordonea5cb932015-05-07 16:28:38 -0700576 public List<PhoneAccountHandle> getCallCapablePhoneAccounts(
Tony Mak240656f2015-12-04 11:36:22 +0000577 String uriScheme, boolean includeDisabledAccounts, UserHandle userHandle) {
Santos Cordonea5cb932015-05-07 16:28:38 -0700578 return getPhoneAccountHandles(
Bryce Leea0bb7052015-10-16 13:31:40 -0700579 PhoneAccount.CAPABILITY_CALL_PROVIDER,
580 PhoneAccount.CAPABILITY_EMERGENCY_CALLS_ONLY /*excludedCapabilities*/,
Tony Mak240656f2015-12-04 11:36:22 +0000581 uriScheme, null, includeDisabledAccounts, userHandle);
582 }
583
Tyler Gunn66ab9ae2017-04-07 15:00:49 -0700584 /**
585 * Retrieves a list of all phone accounts which have
586 * {@link PhoneAccount#CAPABILITY_SELF_MANAGED}.
587 * <p>
588 * Returns only the {@link PhoneAccount}s which are enabled as self-managed accounts are
589 * automatically enabled by default (see {@link #registerPhoneAccount(PhoneAccount)}).
590 *
591 * @param userHandle User handle of phone account owner.
592 * @return The phone account handles.
593 */
594 public List<PhoneAccountHandle> getSelfManagedPhoneAccounts(UserHandle userHandle) {
595 return getPhoneAccountHandles(
596 PhoneAccount.CAPABILITY_SELF_MANAGED,
597 PhoneAccount.CAPABILITY_EMERGENCY_CALLS_ONLY /* excludedCapabilities */,
598 null /* uriScheme */, null /* packageName */, false /* includeDisabledAccounts */,
599 userHandle);
600 }
601
Tony Mak240656f2015-12-04 11:36:22 +0000602 public List<PhoneAccountHandle> getCallCapablePhoneAccountsOfCurrentUser(
603 String uriScheme, boolean includeDisabledAccounts) {
604 return getCallCapablePhoneAccounts(uriScheme, includeDisabledAccounts, mCurrentUserHandle);
Santos Cordon6a212642015-05-08 16:35:23 -0700605 }
606
607 /**
608 * Retrieves a list of all the SIM-based phone accounts.
609 */
Tony Mak240656f2015-12-04 11:36:22 +0000610 public List<PhoneAccountHandle> getSimPhoneAccounts(UserHandle userHandle) {
Santos Cordon6a212642015-05-08 16:35:23 -0700611 return getPhoneAccountHandles(
612 PhoneAccount.CAPABILITY_CALL_PROVIDER | PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION,
Tony Mak240656f2015-12-04 11:36:22 +0000613 null, null, false, userHandle);
Tyler Gunn84253572014-09-02 14:50:05 -0700614 }
615
Tony Mak240656f2015-12-04 11:36:22 +0000616 public List<PhoneAccountHandle> getSimPhoneAccountsOfCurrentUser() {
617 return getSimPhoneAccounts(mCurrentUserHandle);
618 }
619
620 /**
621 * Retrieves a list of all phone accounts registered by a specified package.
622 *
623 * @param packageName The name of the package that registered the phone accounts.
624 * @return The phone account handles.
625 */
626 public List<PhoneAccountHandle> getPhoneAccountsForPackage(String packageName,
627 UserHandle userHandle) {
628 return getPhoneAccountHandles(0, null, packageName, false, userHandle);
Nancy Chen1c5926f2014-09-17 14:44:14 -0700629 }
630
Ihab Awad104f8062014-07-17 11:29:35 -0700631 // TODO: Should we implement an artificial limit for # of accounts associated with a single
632 // ComponentName?
Ihab Awad293edf22014-07-24 17:52:29 -0700633 public void registerPhoneAccount(PhoneAccount account) {
Tyler Gunncb59b672014-08-20 09:02:11 -0700634 // Enforce the requirement that a connection service for a phone account has the correct
635 // permission.
Santos Cordon6a212642015-05-08 16:35:23 -0700636 if (!phoneAccountRequiresBindPermission(account.getAccountHandle())) {
Yorke Lee7bb8ce92015-05-13 16:28:29 -0700637 Log.w(this,
638 "Phone account %s does not have BIND_TELECOM_CONNECTION_SERVICE permission.",
Tyler Gunncb59b672014-08-20 09:02:11 -0700639 account.getAccountHandle());
Yorke Lee7bb8ce92015-05-13 16:28:29 -0700640 throw new SecurityException("PhoneAccount connection service requires "
641 + "BIND_TELECOM_CONNECTION_SERVICE permission.");
Tyler Gunncb59b672014-08-20 09:02:11 -0700642 }
643
Tyler Gunn8e0fef42014-09-08 18:34:44 -0700644 addOrReplacePhoneAccount(account);
645 }
646
647 /**
648 * Adds a {@code PhoneAccount}, replacing an existing one if found.
649 *
650 * @param account The {@code PhoneAccount} to add or replace.
651 */
652 private void addOrReplacePhoneAccount(PhoneAccount account) {
Ihab Awad7e2c7f32014-11-03 09:49:45 -0800653 Log.d(this, "addOrReplacePhoneAccount(%s -> %s)",
654 account.getAccountHandle(), account);
655
Santos Cordonea5cb932015-05-07 16:28:38 -0700656 // Start _enabled_ property as false.
657 // !!! IMPORTANT !!! It is important that we do not read the enabled state that the
658 // source app provides or else an third party app could enable itself.
659 boolean isEnabled = false;
Tyler Gunnea4c6fb2017-04-14 13:46:21 -0700660 boolean isNewAccount;
Santos Cordonea5cb932015-05-07 16:28:38 -0700661
Tony Mak98e6bdc2015-11-25 21:54:05 +0000662 PhoneAccount oldAccount = getPhoneAccountUnchecked(account.getAccountHandle());
Santos Cordon6a212642015-05-08 16:35:23 -0700663 if (oldAccount != null) {
664 mState.accounts.remove(oldAccount);
Santos Cordonea5cb932015-05-07 16:28:38 -0700665 isEnabled = oldAccount.isEnabled();
Tyler Gunnea4c6fb2017-04-14 13:46:21 -0700666 Log.i(this, "Modify account: %s", getAccountDiffString(account, oldAccount));
667 isNewAccount = false;
Santos Cordon5fa4e4f2015-06-10 14:56:01 -0700668 } else {
669 Log.i(this, "New phone account registered: " + account);
Tyler Gunnea4c6fb2017-04-14 13:46:21 -0700670 isNewAccount = true;
Santos Cordon176ae282014-07-14 02:02:14 -0700671 }
Santos Cordonea5cb932015-05-07 16:28:38 -0700672
Tyler Gunn2b17f232017-03-08 08:51:00 -0800673 // When registering a self-managed PhoneAccount we enforce the rule that the label that the
674 // app uses is also its phone account label. Also ensure it does not attempt to declare
675 // itself as a sim acct, call manager or call provider.
676 if (account.hasCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED)) {
677 // Turn off bits we don't want to be able to set (TelecomServiceImpl protects against
678 // this but we'll also prevent it from happening here, just to be safe).
679 int newCapabilities = account.getCapabilities() &
680 ~(PhoneAccount.CAPABILITY_CALL_PROVIDER |
681 PhoneAccount.CAPABILITY_CONNECTION_MANAGER |
682 PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION);
683
684 // Ensure name is correct.
685 CharSequence newLabel = mAppLabelProxy.getAppLabel(
686 account.getAccountHandle().getComponentName().getPackageName());
687
688 account = account.toBuilder()
689 .setLabel(newLabel)
690 .setCapabilities(newCapabilities)
691 .build();
692 }
693
Santos Cordon6a212642015-05-08 16:35:23 -0700694 mState.accounts.add(account);
Srikanth Chintalad5d2dd92016-06-23 16:02:33 +0530695 if (mState.accounts.size() > 1) {
696 mState.accounts.sort(new Comparator<PhoneAccount>() {
697 public int compare(PhoneAccount phoneaccount1, PhoneAccount phoneaccount2) {
698 if (phoneaccount1.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)
699 && phoneaccount2
700 .hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
701 int slotId1 = phoneaccount1.getExtras()
702 .getInt(PhoneAccount.EXTRA_SORT_ORDER);
703 int slotId2 = phoneaccount2.getExtras()
704 .getInt(PhoneAccount.EXTRA_SORT_ORDER);
705 return (slotId1 < slotId2 ? -1 : (slotId1 == slotId2 ? 0 : 1));
706 } else if (phoneaccount1
707 .hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)
708 && !phoneaccount2
709 .hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
710 return -1;
711 } else if (!phoneaccount1
712 .hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)
713 && phoneaccount2
714 .hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
715 return 1;
716 } else {
717 return nullToEmpty(phoneaccount1.getLabel().toString())
718 .compareToIgnoreCase(
719 nullToEmpty(phoneaccount2.getLabel().toString()));
720 }
721 }
722 });
723 }
724
Brad Ebinger0c87b3c2016-06-10 17:23:02 -0700725 // Set defaults and replace based on the group Id.
726 maybeReplaceOldAccount(account);
Santos Cordonea5cb932015-05-07 16:28:38 -0700727 // Reset enabled state to whatever the value was if the account was already registered,
Tyler Gunnacb3bc82017-01-09 09:43:56 -0800728 // or _true_ if this is a SIM-based account. All SIM-based accounts are always enabled,
729 // as are all self-managed phone accounts.
Santos Cordonea5cb932015-05-07 16:28:38 -0700730 account.setIsEnabled(
Tyler Gunnacb3bc82017-01-09 09:43:56 -0800731 isEnabled || account.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)
732 || account.hasCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED));
Santos Cordon176ae282014-07-14 02:02:14 -0700733
Ihab Awad293edf22014-07-24 17:52:29 -0700734 write();
Ihab Awadb78b2762014-07-25 15:16:23 -0700735 fireAccountsChanged();
Tyler Gunnea4c6fb2017-04-14 13:46:21 -0700736 if (isNewAccount) {
737 fireAccountRegistered(account.getAccountHandle());
738 }
Ihab Awad293edf22014-07-24 17:52:29 -0700739 }
740
Evan Charlton89176372014-07-19 18:23:09 -0700741 public void unregisterPhoneAccount(PhoneAccountHandle accountHandle) {
Tony Mak98e6bdc2015-11-25 21:54:05 +0000742 PhoneAccount account = getPhoneAccountUnchecked(accountHandle);
Santos Cordon6a212642015-05-08 16:35:23 -0700743 if (account != null) {
744 if (mState.accounts.remove(account)) {
745 write();
746 fireAccountsChanged();
Tyler Gunnea4c6fb2017-04-14 13:46:21 -0700747 fireAccountUnRegistered(accountHandle);
Ihab Awad104f8062014-07-17 11:29:35 -0700748 }
749 }
Santos Cordon176ae282014-07-14 02:02:14 -0700750 }
751
Tyler Gunnd900ce62014-08-13 11:40:59 -0700752 /**
753 * Un-registers all phone accounts associated with a specified package.
754 *
755 * @param packageName The package for which phone accounts will be removed.
Evan Charlton105d9772014-11-25 14:08:53 -0800756 * @param userHandle The {@link UserHandle} the package is running under.
Tyler Gunnd900ce62014-08-13 11:40:59 -0700757 */
Evan Charlton105d9772014-11-25 14:08:53 -0800758 public void clearAccounts(String packageName, UserHandle userHandle) {
Tyler Gunnd900ce62014-08-13 11:40:59 -0700759 boolean accountsRemoved = false;
760 Iterator<PhoneAccount> it = mState.accounts.iterator();
761 while (it.hasNext()) {
762 PhoneAccount phoneAccount = it.next();
Evan Charlton105d9772014-11-25 14:08:53 -0800763 PhoneAccountHandle handle = phoneAccount.getAccountHandle();
764 if (Objects.equals(packageName, handle.getComponentName().getPackageName())
765 && Objects.equals(userHandle, handle.getUserHandle())) {
Tyler Gunnd900ce62014-08-13 11:40:59 -0700766 Log.i(this, "Removing phone account " + phoneAccount.getLabel());
Shriram Ganesh8f89f8d2015-04-15 12:35:43 +0530767 mState.accounts.remove(phoneAccount);
Tyler Gunnd900ce62014-08-13 11:40:59 -0700768 accountsRemoved = true;
Ihab Awad104f8062014-07-17 11:29:35 -0700769 }
770 }
771
Tyler Gunnd900ce62014-08-13 11:40:59 -0700772 if (accountsRemoved) {
773 write();
774 fireAccountsChanged();
775 }
Ihab Awadb78b2762014-07-25 15:16:23 -0700776 }
777
Nancy Chen140004a2014-10-15 15:48:38 -0700778 public boolean isVoiceMailNumber(PhoneAccountHandle accountHandle, String number) {
Wink Saville35850602014-10-23 15:57:21 -0700779 int subId = getSubscriptionIdForPhoneAccount(accountHandle);
Yorke Leeb1957232015-06-30 10:09:54 -0700780 return PhoneNumberUtils.isVoiceMailNumber(mContext, subId, number);
Nancy Chen140004a2014-10-15 15:48:38 -0700781 }
782
Ihab Awadb78b2762014-07-25 15:16:23 -0700783 public void addListener(Listener l) {
784 mListeners.add(l);
785 }
786
787 public void removeListener(Listener l) {
Jay Shraunera82c8f72014-08-14 15:49:16 -0700788 if (l != null) {
789 mListeners.remove(l);
790 }
Ihab Awadb78b2762014-07-25 15:16:23 -0700791 }
792
Tyler Gunnea4c6fb2017-04-14 13:46:21 -0700793 private void fireAccountRegistered(PhoneAccountHandle handle) {
794 for (Listener l : mListeners) {
795 l.onPhoneAccountRegistered(this, handle);
796 }
797 }
798
799 private void fireAccountUnRegistered(PhoneAccountHandle handle) {
800 for (Listener l : mListeners) {
801 l.onPhoneAccountUnRegistered(this, handle);
802 }
803 }
804
Ihab Awadb78b2762014-07-25 15:16:23 -0700805 private void fireAccountsChanged() {
806 for (Listener l : mListeners) {
807 l.onAccountsChanged(this);
808 }
809 }
810
811 private void fireDefaultOutgoingChanged() {
812 for (Listener l : mListeners) {
813 l.onDefaultOutgoingChanged(this);
814 }
815 }
816
Santos Cordon5fa4e4f2015-06-10 14:56:01 -0700817 private String getAccountDiffString(PhoneAccount account1, PhoneAccount account2) {
818 if (account1 == null || account2 == null) {
819 return "Diff: " + account1 + ", " + account2;
820 }
821
822 StringBuffer sb = new StringBuffer();
823 sb.append("[").append(account1.getAccountHandle());
Anthony Lee7c64a4e2015-08-25 09:27:47 -0700824 appendDiff(sb, "addr", Log.piiHandle(account1.getAddress()),
825 Log.piiHandle(account2.getAddress()));
Santos Cordon5fa4e4f2015-06-10 14:56:01 -0700826 appendDiff(sb, "cap", account1.getCapabilities(), account2.getCapabilities());
827 appendDiff(sb, "hl", account1.getHighlightColor(), account2.getHighlightColor());
Santos Cordon5fa4e4f2015-06-10 14:56:01 -0700828 appendDiff(sb, "lbl", account1.getLabel(), account2.getLabel());
829 appendDiff(sb, "desc", account1.getShortDescription(), account2.getShortDescription());
Anthony Lee7c64a4e2015-08-25 09:27:47 -0700830 appendDiff(sb, "subAddr", Log.piiHandle(account1.getSubscriptionAddress()),
831 Log.piiHandle(account2.getSubscriptionAddress()));
Santos Cordon5fa4e4f2015-06-10 14:56:01 -0700832 appendDiff(sb, "uris", account1.getSupportedUriSchemes(),
833 account2.getSupportedUriSchemes());
834 sb.append("]");
835 return sb.toString();
836 }
837
838 private void appendDiff(StringBuffer sb, String attrName, Object obj1, Object obj2) {
839 if (!Objects.equals(obj1, obj2)) {
840 sb.append("(")
841 .append(attrName)
842 .append(": ")
843 .append(obj1)
844 .append(" -> ")
845 .append(obj2)
846 .append(")");
847 }
848 }
849
Brad Ebinger0c87b3c2016-06-10 17:23:02 -0700850 private void maybeReplaceOldAccount(PhoneAccount newAccount) {
851 UserHandle newAccountUserHandle = newAccount.getAccountHandle().getUserHandle();
852 DefaultPhoneAccountHandle defaultHandle =
853 getUserSelectedDefaultPhoneAccount(newAccountUserHandle);
854 if (defaultHandle == null || defaultHandle.groupId.isEmpty()) {
855 Log.v(this, "maybeReplaceOldAccount: Not replacing PhoneAccount, no group Id or " +
856 "default.");
857 return;
858 }
859 if (!defaultHandle.groupId.equals(newAccount.getGroupId())) {
860 Log.v(this, "maybeReplaceOldAccount: group Ids are not equal.");
861 return;
862 }
863 if (Objects.equals(newAccount.getAccountHandle().getComponentName(),
864 defaultHandle.phoneAccountHandle.getComponentName())) {
865 // Move default calling account over to new user, since the ComponentNames and Group Ids
866 // are the same.
867 setUserSelectedOutgoingPhoneAccount(newAccount.getAccountHandle(),
868 newAccountUserHandle);
869 } else {
870 Log.v(this, "maybeReplaceOldAccount: group Ids are equal, but ComponentName is not" +
871 " the same as the default. Not replacing default PhoneAccount.");
872 }
873 PhoneAccount replacementAccount = getPhoneAccountByGroupId(newAccount.getGroupId(),
874 newAccount.getAccountHandle().getComponentName(), newAccountUserHandle,
875 newAccount.getAccountHandle());
876 if (replacementAccount != null) {
877 // Unregister the old PhoneAccount.
878 Log.v(this, "maybeReplaceOldAccount: Unregistering old PhoneAccount: " +
879 replacementAccount.getAccountHandle());
880 unregisterPhoneAccount(replacementAccount.getAccountHandle());
881 }
882 }
883
Tyler Gunncb59b672014-08-20 09:02:11 -0700884 /**
Santos Cordon6a212642015-05-08 16:35:23 -0700885 * Determines if the connection service specified by a {@link PhoneAccountHandle} requires the
Yorke Lee7bb8ce92015-05-13 16:28:29 -0700886 * {@link Manifest.permission#BIND_TELECOM_CONNECTION_SERVICE} permission.
Tyler Gunncb59b672014-08-20 09:02:11 -0700887 *
888 * @param phoneAccountHandle The phone account to check.
889 * @return {@code True} if the phone account has permission.
890 */
Santos Cordon6a212642015-05-08 16:35:23 -0700891 public boolean phoneAccountRequiresBindPermission(PhoneAccountHandle phoneAccountHandle) {
Sailesh Nepal91fc8092015-02-14 15:44:55 -0800892 List<ResolveInfo> resolveInfos = resolveComponent(phoneAccountHandle);
893 if (resolveInfos.isEmpty()) {
894 Log.w(this, "phoneAccount %s not found", phoneAccountHandle.getComponentName());
Tyler Gunncb59b672014-08-20 09:02:11 -0700895 return false;
896 }
Sailesh Nepal91fc8092015-02-14 15:44:55 -0800897 for (ResolveInfo resolveInfo : resolveInfos) {
898 ServiceInfo serviceInfo = resolveInfo.serviceInfo;
Yorke Lee7bb8ce92015-05-13 16:28:29 -0700899 if (serviceInfo == null) {
900 return false;
901 }
902
903 if (!Manifest.permission.BIND_CONNECTION_SERVICE.equals(serviceInfo.permission) &&
904 !Manifest.permission.BIND_TELECOM_CONNECTION_SERVICE.equals(
905 serviceInfo.permission)) {
906 // The ConnectionService must require either the deprecated BIND_CONNECTION_SERVICE,
907 // or the public BIND_TELECOM_CONNECTION_SERVICE permissions, both of which are
908 // system/signature only.
Sailesh Nepal91fc8092015-02-14 15:44:55 -0800909 return false;
910 }
911 }
912 return true;
Tyler Gunncb59b672014-08-20 09:02:11 -0700913 }
914
Santos Cordon6a212642015-05-08 16:35:23 -0700915 //
916 // Methods for retrieving PhoneAccounts and PhoneAccountHandles
917 //
Ihab Awad293edf22014-07-24 17:52:29 -0700918
Santos Cordonafe59e52014-08-22 16:48:43 -0700919 /**
Santos Cordon6a212642015-05-08 16:35:23 -0700920 * Returns the PhoneAccount for the specified handle. Does no user checking.
Tyler Gunn84253572014-09-02 14:50:05 -0700921 *
Santos Cordon6a212642015-05-08 16:35:23 -0700922 * @param handle
923 * @return The corresponding phone account if one exists.
Santos Cordonafe59e52014-08-22 16:48:43 -0700924 */
Tony Mak98e6bdc2015-11-25 21:54:05 +0000925 public PhoneAccount getPhoneAccountUnchecked(PhoneAccountHandle handle) {
Santos Cordon6a212642015-05-08 16:35:23 -0700926 for (PhoneAccount m : mState.accounts) {
927 if (Objects.equals(handle, m.getAccountHandle())) {
928 return m;
929 }
930 }
931 return null;
932 }
933
934 /**
935 * Like getPhoneAccount, but checks to see if the current user is allowed to see the phone
936 * account before returning it. The current user is the active user on the actual android
937 * device.
938 */
Tony Mak240656f2015-12-04 11:36:22 +0000939 public PhoneAccount getPhoneAccount(PhoneAccountHandle handle, UserHandle userHandle) {
940 return getPhoneAccount(handle, userHandle, /* acrossProfiles */ false);
941 }
942
943 public PhoneAccount getPhoneAccount(PhoneAccountHandle handle,
944 UserHandle userHandle, boolean acrossProfiles) {
Tony Mak98e6bdc2015-11-25 21:54:05 +0000945 PhoneAccount account = getPhoneAccountUnchecked(handle);
Tony Mak240656f2015-12-04 11:36:22 +0000946 if (account != null && (isVisibleForUser(account, userHandle, acrossProfiles))) {
Santos Cordon6a212642015-05-08 16:35:23 -0700947 return account;
948 }
949 return null;
950 }
951
Tony Mak240656f2015-12-04 11:36:22 +0000952 public PhoneAccount getPhoneAccountOfCurrentUser(PhoneAccountHandle handle) {
953 return getPhoneAccount(handle, mCurrentUserHandle);
954 }
955
Bryce Leea0bb7052015-10-16 13:31:40 -0700956 private List<PhoneAccountHandle> getPhoneAccountHandles(
957 int capabilities,
958 String uriScheme,
959 String packageName,
Tony Mak240656f2015-12-04 11:36:22 +0000960 boolean includeDisabledAccounts,
961 UserHandle userHandle) {
Bryce Leea0bb7052015-10-16 13:31:40 -0700962 return getPhoneAccountHandles(capabilities, 0 /*excludedCapabilities*/, uriScheme,
Tony Mak240656f2015-12-04 11:36:22 +0000963 packageName, includeDisabledAccounts, userHandle);
Bryce Leea0bb7052015-10-16 13:31:40 -0700964 }
965
Santos Cordon6a212642015-05-08 16:35:23 -0700966 /**
967 * Returns a list of phone account handles with the specified capabilities, uri scheme,
968 * and package name.
969 */
970 private List<PhoneAccountHandle> getPhoneAccountHandles(
Santos Cordonea5cb932015-05-07 16:28:38 -0700971 int capabilities,
Bryce Leea0bb7052015-10-16 13:31:40 -0700972 int excludedCapabilities,
Santos Cordonea5cb932015-05-07 16:28:38 -0700973 String uriScheme,
974 String packageName,
Tony Mak240656f2015-12-04 11:36:22 +0000975 boolean includeDisabledAccounts,
976 UserHandle userHandle) {
Santos Cordon6a212642015-05-08 16:35:23 -0700977 List<PhoneAccountHandle> handles = new ArrayList<>();
Santos Cordonea5cb932015-05-07 16:28:38 -0700978
979 for (PhoneAccount account : getPhoneAccounts(
Bryce Leea0bb7052015-10-16 13:31:40 -0700980 capabilities, excludedCapabilities, uriScheme, packageName,
Tony Mak240656f2015-12-04 11:36:22 +0000981 includeDisabledAccounts, userHandle)) {
Santos Cordon6a212642015-05-08 16:35:23 -0700982 handles.add(account.getAccountHandle());
983 }
984 return handles;
Tyler Gunn84253572014-09-02 14:50:05 -0700985 }
986
Bryce Leea0bb7052015-10-16 13:31:40 -0700987 private List<PhoneAccount> getPhoneAccounts(
988 int capabilities,
989 String uriScheme,
990 String packageName,
Tony Mak240656f2015-12-04 11:36:22 +0000991 boolean includeDisabledAccounts,
992 UserHandle userHandle) {
Bryce Leea0bb7052015-10-16 13:31:40 -0700993 return getPhoneAccounts(capabilities, 0 /*excludedCapabilities*/, uriScheme, packageName,
Tony Mak240656f2015-12-04 11:36:22 +0000994 includeDisabledAccounts, userHandle);
Bryce Leea0bb7052015-10-16 13:31:40 -0700995 }
996
Tyler Gunn84253572014-09-02 14:50:05 -0700997 /**
998 * Returns a list of phone account handles with the specified flag, supporting the specified
Santos Cordon6a212642015-05-08 16:35:23 -0700999 * URI scheme, within the specified package name.
Tyler Gunn84253572014-09-02 14:50:05 -07001000 *
Santos Cordon6a212642015-05-08 16:35:23 -07001001 * @param capabilities Capabilities which the {@code PhoneAccount} must have. Ignored if 0.
Bryce Leea0bb7052015-10-16 13:31:40 -07001002 * @param excludedCapabilities Capabilities which the {@code PhoneAccount} must not have.
1003 * Ignored if 0.
Santos Cordon6a212642015-05-08 16:35:23 -07001004 * @param uriScheme URI schemes the PhoneAccount must handle. {@code null} bypasses the
Tyler Gunn84253572014-09-02 14:50:05 -07001005 * URI scheme check.
Santos Cordon6a212642015-05-08 16:35:23 -07001006 * @param packageName Package name of the PhoneAccount. {@code null} bypasses packageName check.
Tyler Gunn84253572014-09-02 14:50:05 -07001007 */
Santos Cordon6a212642015-05-08 16:35:23 -07001008 private List<PhoneAccount> getPhoneAccounts(
Santos Cordonea5cb932015-05-07 16:28:38 -07001009 int capabilities,
Bryce Leea0bb7052015-10-16 13:31:40 -07001010 int excludedCapabilities,
Santos Cordonea5cb932015-05-07 16:28:38 -07001011 String uriScheme,
1012 String packageName,
Tony Mak240656f2015-12-04 11:36:22 +00001013 boolean includeDisabledAccounts,
1014 UserHandle userHandle) {
Santos Cordon6a212642015-05-08 16:35:23 -07001015 List<PhoneAccount> accounts = new ArrayList<>(mState.accounts.size());
Ihab Awad293edf22014-07-24 17:52:29 -07001016 for (PhoneAccount m : mState.accounts) {
Santos Cordonea5cb932015-05-07 16:28:38 -07001017 if (!(m.isEnabled() || includeDisabledAccounts)) {
1018 // Do not include disabled accounts.
1019 continue;
1020 }
1021
Bryce Leea0bb7052015-10-16 13:31:40 -07001022 if ((m.getCapabilities() & excludedCapabilities) != 0) {
1023 // If an excluded capability is present, skip.
1024 continue;
1025 }
1026
Santos Cordon6a212642015-05-08 16:35:23 -07001027 if (capabilities != 0 && !m.hasCapabilities(capabilities)) {
Evan Charlton105d9772014-11-25 14:08:53 -08001028 // Account doesn't have the right capabilities; skip this one.
1029 continue;
Ihab Awadf2a84912014-07-22 21:09:25 -07001030 }
Evan Charlton105d9772014-11-25 14:08:53 -08001031 if (uriScheme != null && !m.supportsUriScheme(uriScheme)) {
1032 // Account doesn't support this URI scheme; skip this one.
1033 continue;
1034 }
Santos Cordon6a212642015-05-08 16:35:23 -07001035 PhoneAccountHandle handle = m.getAccountHandle();
1036
1037 if (resolveComponent(handle).isEmpty()) {
Evan Charlton105d9772014-11-25 14:08:53 -08001038 // This component cannot be resolved anymore; skip this one.
1039 continue;
1040 }
Santos Cordon6a212642015-05-08 16:35:23 -07001041 if (packageName != null &&
1042 !packageName.equals(handle.getComponentName().getPackageName())) {
1043 // Not the right package name; skip this one.
1044 continue;
1045 }
Tony Mak240656f2015-12-04 11:36:22 +00001046 if (!isVisibleForUser(m, userHandle, false)) {
Evan Charlton105d9772014-11-25 14:08:53 -08001047 // Account is not visible for the current user; skip this one.
1048 continue;
1049 }
Santos Cordon6a212642015-05-08 16:35:23 -07001050 accounts.add(m);
Ihab Awad104f8062014-07-17 11:29:35 -07001051 }
Santos Cordon6a212642015-05-08 16:35:23 -07001052 return accounts;
Ihab Awad104f8062014-07-17 11:29:35 -07001053 }
1054
Santos Cordon6a212642015-05-08 16:35:23 -07001055 //
1056 // State Implementation for PhoneAccountRegistrar
1057 //
1058
Ihab Awad293edf22014-07-24 17:52:29 -07001059 /**
1060 * The state of this {@code PhoneAccountRegistrar}.
1061 */
Ihab Awadb78b2762014-07-25 15:16:23 -07001062 @VisibleForTesting
1063 public static class State {
Ihab Awad293edf22014-07-24 17:52:29 -07001064 /**
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001065 * Store the default phone account handle of users. If no record of a user can be found in
1066 * the map, it means that no default phone account handle is set in that user.
Ihab Awad293edf22014-07-24 17:52:29 -07001067 */
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001068 public final Map<UserHandle, DefaultPhoneAccountHandle> defaultOutgoingAccountHandles
1069 = new ConcurrentHashMap<>();
Ihab Awad293edf22014-07-24 17:52:29 -07001070
1071 /**
Tyler Gunn7cc70b42014-09-12 22:17:27 -07001072 * The complete list of {@code PhoneAccount}s known to the Telecom subsystem.
Ihab Awad293edf22014-07-24 17:52:29 -07001073 */
Shriram Ganesh8f89f8d2015-04-15 12:35:43 +05301074 public final List<PhoneAccount> accounts = new CopyOnWriteArrayList<>();
Tyler Gunn84253572014-09-02 14:50:05 -07001075
1076 /**
1077 * The version number of the State data.
1078 */
1079 public int versionNumber;
Ihab Awad293edf22014-07-24 17:52:29 -07001080 }
1081
Tyler Gunn9787e0e2014-10-14 14:36:12 -07001082 /**
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001083 * The default {@link PhoneAccountHandle} of a user.
1084 */
1085 public static class DefaultPhoneAccountHandle {
1086
1087 public final UserHandle userHandle;
1088
1089 public final PhoneAccountHandle phoneAccountHandle;
1090
Brad Ebinger0c87b3c2016-06-10 17:23:02 -07001091 public final String groupId;
1092
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001093 public DefaultPhoneAccountHandle(UserHandle userHandle,
Brad Ebinger0c87b3c2016-06-10 17:23:02 -07001094 PhoneAccountHandle phoneAccountHandle, String groupId) {
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001095 this.userHandle = userHandle;
1096 this.phoneAccountHandle = phoneAccountHandle;
Brad Ebinger0c87b3c2016-06-10 17:23:02 -07001097 this.groupId = groupId;
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001098 }
1099 }
1100
1101 /**
Tyler Gunn9787e0e2014-10-14 14:36:12 -07001102 * Dumps the state of the {@link CallsManager}.
1103 *
1104 * @param pw The {@code IndentingPrintWriter} to write the state to.
1105 */
1106 public void dump(IndentingPrintWriter pw) {
1107 if (mState != null) {
1108 pw.println("xmlVersion: " + mState.versionNumber);
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001109 DefaultPhoneAccountHandle defaultPhoneAccountHandle
1110 = mState.defaultOutgoingAccountHandles.get(Process.myUserHandle());
1111 pw.println("defaultOutgoing: " + (defaultPhoneAccountHandle == null ? "none" :
1112 defaultPhoneAccountHandle.phoneAccountHandle));
Tony Mak240656f2015-12-04 11:36:22 +00001113 pw.println("simCallManager: " + getSimCallManager(mCurrentUserHandle));
Tyler Gunn9787e0e2014-10-14 14:36:12 -07001114 pw.println("phoneAccounts:");
1115 pw.increaseIndent();
1116 for (PhoneAccount phoneAccount : mState.accounts) {
1117 pw.println(phoneAccount);
1118 }
1119 pw.decreaseIndent();
1120 }
1121 }
1122
Ihab Awad293edf22014-07-24 17:52:29 -07001123 ////////////////////////////////////////////////////////////////////////////////////////////////
1124 //
1125 // State management
1126 //
1127
Hall Liu3f7f64d2016-01-07 17:40:13 -08001128 private class AsyncXmlWriter extends AsyncTask<ByteArrayOutputStream, Void, Void> {
1129 @Override
1130 public Void doInBackground(ByteArrayOutputStream... args) {
1131 final ByteArrayOutputStream buffer = args[0];
1132 FileOutputStream fileOutput = null;
Ihab Awadb78b2762014-07-25 15:16:23 -07001133 try {
Hall Liu3f7f64d2016-01-07 17:40:13 -08001134 synchronized (mWriteLock) {
1135 fileOutput = mAtomicFile.startWrite();
1136 buffer.writeTo(fileOutput);
1137 mAtomicFile.finishWrite(fileOutput);
Ihab Awadb78b2762014-07-25 15:16:23 -07001138 }
Hall Liu3f7f64d2016-01-07 17:40:13 -08001139 } catch (IOException e) {
1140 Log.e(this, e, "Writing state to XML file");
1141 mAtomicFile.failWrite(fileOutput);
Ihab Awadb78b2762014-07-25 15:16:23 -07001142 }
Hall Liu3f7f64d2016-01-07 17:40:13 -08001143 return null;
1144 }
1145 }
1146
1147 private void write() {
1148 try {
1149 ByteArrayOutputStream os = new ByteArrayOutputStream();
1150 XmlSerializer serializer = new FastXmlSerializer();
1151 serializer.setOutput(os, "utf-8");
1152 writeToXml(mState, serializer, mContext);
1153 serializer.flush();
1154 new AsyncXmlWriter().execute(os);
Ihab Awadb78b2762014-07-25 15:16:23 -07001155 } catch (IOException e) {
Hall Liu3f7f64d2016-01-07 17:40:13 -08001156 Log.e(this, e, "Writing state to XML buffer");
Ihab Awad104f8062014-07-17 11:29:35 -07001157 }
1158 }
1159
Ihab Awadb78b2762014-07-25 15:16:23 -07001160 private void read() {
1161 final InputStream is;
Ihab Awad104f8062014-07-17 11:29:35 -07001162 try {
Ihab Awadb78b2762014-07-25 15:16:23 -07001163 is = mAtomicFile.openRead();
1164 } catch (FileNotFoundException ex) {
1165 return;
1166 }
1167
Tyler Gunn84253572014-09-02 14:50:05 -07001168 boolean versionChanged = false;
1169
Ihab Awadb78b2762014-07-25 15:16:23 -07001170 XmlPullParser parser;
1171 try {
1172 parser = Xml.newPullParser();
1173 parser.setInput(new BufferedInputStream(is), null);
1174 parser.nextTag();
Tyler Gunn84253572014-09-02 14:50:05 -07001175 mState = readFromXml(parser, mContext);
1176 versionChanged = mState.versionNumber < EXPECTED_STATE_VERSION;
1177
Ihab Awadb78b2762014-07-25 15:16:23 -07001178 } catch (IOException | XmlPullParserException e) {
1179 Log.e(this, e, "Reading state from XML file");
1180 mState = new State();
1181 } finally {
1182 try {
1183 is.close();
1184 } catch (IOException e) {
1185 Log.e(this, e, "Closing InputStream");
1186 }
Ihab Awad104f8062014-07-17 11:29:35 -07001187 }
Tyler Gunn84253572014-09-02 14:50:05 -07001188
Evan Charlton105d9772014-11-25 14:08:53 -08001189 // Verify all of the UserHandles.
1190 List<PhoneAccount> badAccounts = new ArrayList<>();
1191 for (PhoneAccount phoneAccount : mState.accounts) {
1192 UserHandle userHandle = phoneAccount.getAccountHandle().getUserHandle();
1193 if (userHandle == null) {
1194 Log.w(this, "Missing UserHandle for %s", phoneAccount);
1195 badAccounts.add(phoneAccount);
1196 } else if (mUserManager.getSerialNumberForUser(userHandle) == -1) {
1197 Log.w(this, "User does not exist for %s", phoneAccount);
1198 badAccounts.add(phoneAccount);
1199 }
1200 }
1201 mState.accounts.removeAll(badAccounts);
1202
Tyler Gunn84253572014-09-02 14:50:05 -07001203 // If an upgrade occurred, write out the changed data.
Evan Charlton105d9772014-11-25 14:08:53 -08001204 if (versionChanged || !badAccounts.isEmpty()) {
Tyler Gunn84253572014-09-02 14:50:05 -07001205 write();
1206 }
Santos Cordon176ae282014-07-14 02:02:14 -07001207 }
1208
Evan Charlton105d9772014-11-25 14:08:53 -08001209 private static void writeToXml(State state, XmlSerializer serializer, Context context)
Ihab Awadb78b2762014-07-25 15:16:23 -07001210 throws IOException {
Evan Charlton105d9772014-11-25 14:08:53 -08001211 sStateXml.writeToXml(state, serializer, context);
Santos Cordon176ae282014-07-14 02:02:14 -07001212 }
Ihab Awad104f8062014-07-17 11:29:35 -07001213
Tyler Gunn84253572014-09-02 14:50:05 -07001214 private static State readFromXml(XmlPullParser parser, Context context)
Ihab Awadb78b2762014-07-25 15:16:23 -07001215 throws IOException, XmlPullParserException {
Tyler Gunn84253572014-09-02 14:50:05 -07001216 State s = sStateXml.readFromXml(parser, 0, context);
Ihab Awadb78b2762014-07-25 15:16:23 -07001217 return s != null ? s : new State();
Ihab Awad104f8062014-07-17 11:29:35 -07001218 }
1219
Ihab Awad293edf22014-07-24 17:52:29 -07001220 ////////////////////////////////////////////////////////////////////////////////////////////////
Ihab Awad104f8062014-07-17 11:29:35 -07001221 //
Ihab Awadb78b2762014-07-25 15:16:23 -07001222 // XML serialization
Ihab Awad104f8062014-07-17 11:29:35 -07001223 //
1224
Ihab Awadb78b2762014-07-25 15:16:23 -07001225 @VisibleForTesting
Ihab Awad26923222014-07-30 10:54:35 -07001226 public abstract static class XmlSerialization<T> {
Tyler Gunn369c8742015-10-07 15:39:28 -07001227 private static final String TAG_VALUE = "value";
1228 private static final String ATTRIBUTE_LENGTH = "length";
1229 private static final String ATTRIBUTE_KEY = "key";
1230 private static final String ATTRIBUTE_VALUE_TYPE = "type";
1231 private static final String VALUE_TYPE_STRING = "string";
1232 private static final String VALUE_TYPE_INTEGER = "integer";
1233 private static final String VALUE_TYPE_BOOLEAN = "boolean";
Tyler Gunn84253572014-09-02 14:50:05 -07001234
Ihab Awadb78b2762014-07-25 15:16:23 -07001235 /**
1236 * Write the supplied object to XML
1237 */
Evan Charlton105d9772014-11-25 14:08:53 -08001238 public abstract void writeToXml(T o, XmlSerializer serializer, Context context)
Ihab Awad26923222014-07-30 10:54:35 -07001239 throws IOException;
Ihab Awadb78b2762014-07-25 15:16:23 -07001240
1241 /**
1242 * Read from the supplied XML into a new object, returning null in case of an
1243 * unrecoverable schema mismatch or other data error. 'parser' must be already
1244 * positioned at the first tag that is expected to have been emitted by this
1245 * object's writeToXml(). This object tries to fail early without modifying
1246 * 'parser' if it does not recognize the data it sees.
1247 */
Tyler Gunn84253572014-09-02 14:50:05 -07001248 public abstract T readFromXml(XmlPullParser parser, int version, Context context)
Ihab Awad26923222014-07-30 10:54:35 -07001249 throws IOException, XmlPullParserException;
1250
Ihab Awadd9f54382014-10-24 11:44:47 -07001251 protected void writeTextIfNonNull(String tagName, Object value, XmlSerializer serializer)
Ihab Awad26923222014-07-30 10:54:35 -07001252 throws IOException {
1253 if (value != null) {
1254 serializer.startTag(null, tagName);
1255 serializer.text(Objects.toString(value));
1256 serializer.endTag(null, tagName);
1257 }
1258 }
Tyler Gunn84253572014-09-02 14:50:05 -07001259
1260 /**
1261 * Serializes a string array.
1262 *
1263 * @param tagName The tag name for the string array.
1264 * @param values The string values to serialize.
1265 * @param serializer The serializer.
1266 * @throws IOException
1267 */
1268 protected void writeStringList(String tagName, List<String> values,
1269 XmlSerializer serializer)
1270 throws IOException {
1271
1272 serializer.startTag(null, tagName);
1273 if (values != null) {
Tyler Gunn369c8742015-10-07 15:39:28 -07001274 serializer.attribute(null, ATTRIBUTE_LENGTH, Objects.toString(values.size()));
Tyler Gunn84253572014-09-02 14:50:05 -07001275 for (String toSerialize : values) {
Tyler Gunn369c8742015-10-07 15:39:28 -07001276 serializer.startTag(null, TAG_VALUE);
Tyler Gunn84253572014-09-02 14:50:05 -07001277 if (toSerialize != null ){
1278 serializer.text(toSerialize);
1279 }
Tyler Gunn369c8742015-10-07 15:39:28 -07001280 serializer.endTag(null, TAG_VALUE);
Tyler Gunn84253572014-09-02 14:50:05 -07001281 }
1282 } else {
Tyler Gunn369c8742015-10-07 15:39:28 -07001283 serializer.attribute(null, ATTRIBUTE_LENGTH, "0");
1284 }
1285 serializer.endTag(null, tagName);
1286 }
1287
1288 protected void writeBundle(String tagName, Bundle values, XmlSerializer serializer)
1289 throws IOException {
1290
1291 serializer.startTag(null, tagName);
1292 if (values != null) {
1293 for (String key : values.keySet()) {
1294 Object value = values.get(key);
1295
1296 if (value == null) {
1297 continue;
1298 }
1299
1300 String valueType;
1301 if (value instanceof String) {
1302 valueType = VALUE_TYPE_STRING;
1303 } else if (value instanceof Integer) {
1304 valueType = VALUE_TYPE_INTEGER;
1305 } else if (value instanceof Boolean) {
1306 valueType = VALUE_TYPE_BOOLEAN;
1307 } else {
1308 Log.w(this,
1309 "PhoneAccounts support only string, integer and boolean extras TY.");
1310 continue;
1311 }
1312
1313 serializer.startTag(null, TAG_VALUE);
1314 serializer.attribute(null, ATTRIBUTE_KEY, key);
1315 serializer.attribute(null, ATTRIBUTE_VALUE_TYPE, valueType);
1316 serializer.text(Objects.toString(value));
1317 serializer.endTag(null, TAG_VALUE);
1318 }
Tyler Gunn84253572014-09-02 14:50:05 -07001319 }
1320 serializer.endTag(null, tagName);
Ihab Awadd9f54382014-10-24 11:44:47 -07001321 }
Tyler Gunn84253572014-09-02 14:50:05 -07001322
Santos Cordon9c30c282015-05-13 16:28:27 -07001323 protected void writeIconIfNonNull(String tagName, Icon value, XmlSerializer serializer)
Ihab Awadd9f54382014-10-24 11:44:47 -07001324 throws IOException {
Santos Cordon9c30c282015-05-13 16:28:27 -07001325 if (value != null) {
Ihab Awadd9f54382014-10-24 11:44:47 -07001326 ByteArrayOutputStream stream = new ByteArrayOutputStream();
Santos Cordon9c30c282015-05-13 16:28:27 -07001327 value.writeToStream(stream);
1328 byte[] iconByteArray = stream.toByteArray();
1329 String text = Base64.encodeToString(iconByteArray, 0, iconByteArray.length, 0);
Ihab Awadd9f54382014-10-24 11:44:47 -07001330
1331 serializer.startTag(null, tagName);
1332 serializer.text(text);
1333 serializer.endTag(null, tagName);
1334 }
Tyler Gunn84253572014-09-02 14:50:05 -07001335 }
1336
Evan Charlton105d9772014-11-25 14:08:53 -08001337 protected void writeLong(String tagName, long value, XmlSerializer serializer)
1338 throws IOException {
1339 serializer.startTag(null, tagName);
1340 serializer.text(Long.valueOf(value).toString());
1341 serializer.endTag(null, tagName);
1342 }
1343
Brad Ebinger0c87b3c2016-06-10 17:23:02 -07001344 protected void writeNonNullString(String tagName, String value, XmlSerializer serializer)
1345 throws IOException {
1346 serializer.startTag(null, tagName);
1347 serializer.text(value != null ? value : "");
1348 serializer.endTag(null, tagName);
1349 }
1350
Tyler Gunn84253572014-09-02 14:50:05 -07001351 /**
1352 * Reads a string array from the XML parser.
1353 *
1354 * @param parser The XML parser.
1355 * @return String array containing the parsed values.
1356 * @throws IOException Exception related to IO.
1357 * @throws XmlPullParserException Exception related to parsing.
1358 */
1359 protected List<String> readStringList(XmlPullParser parser)
1360 throws IOException, XmlPullParserException {
1361
Tyler Gunn369c8742015-10-07 15:39:28 -07001362 int length = Integer.parseInt(parser.getAttributeValue(null, ATTRIBUTE_LENGTH));
Tyler Gunn84253572014-09-02 14:50:05 -07001363 List<String> arrayEntries = new ArrayList<String>(length);
1364 String value = null;
1365
1366 if (length == 0) {
1367 return arrayEntries;
1368 }
1369
1370 int outerDepth = parser.getDepth();
1371 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
Tyler Gunn369c8742015-10-07 15:39:28 -07001372 if (parser.getName().equals(TAG_VALUE)) {
Tyler Gunn8e0fef42014-09-08 18:34:44 -07001373 parser.next();
Tyler Gunn84253572014-09-02 14:50:05 -07001374 value = parser.getText();
1375 arrayEntries.add(value);
1376 }
1377 }
1378
1379 return arrayEntries;
1380 }
Ihab Awadd9f54382014-10-24 11:44:47 -07001381
Tyler Gunn369c8742015-10-07 15:39:28 -07001382 /**
1383 * Reads a bundle from the XML parser.
1384 *
1385 * @param parser The XML parser.
1386 * @return Bundle containing the parsed values.
1387 * @throws IOException Exception related to IO.
1388 * @throws XmlPullParserException Exception related to parsing.
1389 */
1390 protected Bundle readBundle(XmlPullParser parser)
1391 throws IOException, XmlPullParserException {
1392
1393 Bundle bundle = null;
1394 int outerDepth = parser.getDepth();
1395 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1396 if (parser.getName().equals(TAG_VALUE)) {
1397 String valueType = parser.getAttributeValue(null, ATTRIBUTE_VALUE_TYPE);
1398 String key = parser.getAttributeValue(null, ATTRIBUTE_KEY);
1399 parser.next();
1400 String value = parser.getText();
1401
1402 if (bundle == null) {
1403 bundle = new Bundle();
1404 }
1405
1406 // Do not write null values to the bundle.
1407 if (value == null) {
1408 continue;
1409 }
1410
1411 if (VALUE_TYPE_STRING.equals(valueType)) {
1412 bundle.putString(key, value);
1413 } else if (VALUE_TYPE_INTEGER.equals(valueType)) {
1414 try {
1415 int intValue = Integer.parseInt(value);
1416 bundle.putInt(key, intValue);
1417 } catch (NumberFormatException nfe) {
1418 Log.w(this, "Invalid integer PhoneAccount extra.");
1419 }
1420 } else if (VALUE_TYPE_BOOLEAN.equals(valueType)) {
1421 boolean boolValue = Boolean.parseBoolean(value);
1422 bundle.putBoolean(key, boolValue);
1423 } else {
1424 Log.w(this, "Invalid type " + valueType + " for PhoneAccount bundle.");
1425 }
1426 }
1427 }
1428 return bundle;
1429 }
1430
Santos Cordon9c30c282015-05-13 16:28:27 -07001431 protected Bitmap readBitmap(XmlPullParser parser) {
Ihab Awadd9f54382014-10-24 11:44:47 -07001432 byte[] imageByteArray = Base64.decode(parser.getText(), 0);
1433 return BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
1434 }
Santos Cordon9c30c282015-05-13 16:28:27 -07001435
1436 protected Icon readIcon(XmlPullParser parser) throws IOException {
1437 byte[] iconByteArray = Base64.decode(parser.getText(), 0);
1438 ByteArrayInputStream stream = new ByteArrayInputStream(iconByteArray);
1439 return Icon.createFromStream(stream);
1440 }
Ihab Awad104f8062014-07-17 11:29:35 -07001441 }
1442
Ihab Awadb78b2762014-07-25 15:16:23 -07001443 @VisibleForTesting
1444 public static final XmlSerialization<State> sStateXml =
1445 new XmlSerialization<State>() {
1446 private static final String CLASS_STATE = "phone_account_registrar_state";
Ihab Awad104f8062014-07-17 11:29:35 -07001447 private static final String DEFAULT_OUTGOING = "default_outgoing";
1448 private static final String ACCOUNTS = "accounts";
Tyler Gunn84253572014-09-02 14:50:05 -07001449 private static final String VERSION = "version";
Ihab Awad104f8062014-07-17 11:29:35 -07001450
1451 @Override
Evan Charlton105d9772014-11-25 14:08:53 -08001452 public void writeToXml(State o, XmlSerializer serializer, Context context)
Ihab Awadb78b2762014-07-25 15:16:23 -07001453 throws IOException {
Ihab Awad26923222014-07-30 10:54:35 -07001454 if (o != null) {
1455 serializer.startTag(null, CLASS_STATE);
Tyler Gunn84253572014-09-02 14:50:05 -07001456 serializer.attribute(null, VERSION, Objects.toString(EXPECTED_STATE_VERSION));
Ihab Awadb78b2762014-07-25 15:16:23 -07001457
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001458 serializer.startTag(null, DEFAULT_OUTGOING);
1459 for (DefaultPhoneAccountHandle defaultPhoneAccountHandle : o
1460 .defaultOutgoingAccountHandles.values()) {
1461 sDefaultPhoneAcountHandleXml
1462 .writeToXml(defaultPhoneAccountHandle, serializer, context);
Ihab Awad26923222014-07-30 10:54:35 -07001463 }
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001464 serializer.endTag(null, DEFAULT_OUTGOING);
Ihab Awad26923222014-07-30 10:54:35 -07001465
Ihab Awad26923222014-07-30 10:54:35 -07001466 serializer.startTag(null, ACCOUNTS);
1467 for (PhoneAccount m : o.accounts) {
Evan Charlton105d9772014-11-25 14:08:53 -08001468 sPhoneAccountXml.writeToXml(m, serializer, context);
Ihab Awad26923222014-07-30 10:54:35 -07001469 }
1470 serializer.endTag(null, ACCOUNTS);
1471
1472 serializer.endTag(null, CLASS_STATE);
Ihab Awad293edf22014-07-24 17:52:29 -07001473 }
Ihab Awad104f8062014-07-17 11:29:35 -07001474 }
1475
1476 @Override
Tyler Gunn84253572014-09-02 14:50:05 -07001477 public State readFromXml(XmlPullParser parser, int version, Context context)
Ihab Awadb78b2762014-07-25 15:16:23 -07001478 throws IOException, XmlPullParserException {
1479 if (parser.getName().equals(CLASS_STATE)) {
1480 State s = new State();
Tyler Gunn84253572014-09-02 14:50:05 -07001481
1482 String rawVersion = parser.getAttributeValue(null, VERSION);
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001483 s.versionNumber = TextUtils.isEmpty(rawVersion) ? 1 : Integer.parseInt(rawVersion);
Tyler Gunn84253572014-09-02 14:50:05 -07001484
Ihab Awadb78b2762014-07-25 15:16:23 -07001485 int outerDepth = parser.getDepth();
1486 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1487 if (parser.getName().equals(DEFAULT_OUTGOING)) {
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001488 if (s.versionNumber < 9) {
Brad Ebinger0c87b3c2016-06-10 17:23:02 -07001489 // Migrate old default phone account handle here by assuming the
1490 // default phone account handle belongs to the primary user. Also,
1491 // assume there are no groups.
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001492 parser.nextTag();
1493 PhoneAccountHandle phoneAccountHandle = sPhoneAccountHandleXml
1494 .readFromXml(parser, s.versionNumber, context);
1495 UserManager userManager = UserManager.get(context);
1496 UserInfo primaryUser = userManager.getPrimaryUser();
1497 if (primaryUser != null) {
1498 UserHandle userHandle = primaryUser.getUserHandle();
1499 DefaultPhoneAccountHandle defaultPhoneAccountHandle
1500 = new DefaultPhoneAccountHandle(userHandle,
Brad Ebinger0c87b3c2016-06-10 17:23:02 -07001501 phoneAccountHandle, "" /* groupId */);
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001502 s.defaultOutgoingAccountHandles
1503 .put(userHandle, defaultPhoneAccountHandle);
1504 }
1505 } else {
1506 int defaultAccountHandlesDepth = parser.getDepth();
1507 while (XmlUtils.nextElementWithin(parser, defaultAccountHandlesDepth)) {
1508 DefaultPhoneAccountHandle accountHandle
1509 = sDefaultPhoneAcountHandleXml
1510 .readFromXml(parser, s.versionNumber, context);
1511 if (accountHandle != null && s.accounts != null) {
1512 s.defaultOutgoingAccountHandles
1513 .put(accountHandle.userHandle, accountHandle);
1514 }
1515 }
1516 }
Ihab Awadb78b2762014-07-25 15:16:23 -07001517 } else if (parser.getName().equals(ACCOUNTS)) {
1518 int accountsDepth = parser.getDepth();
1519 while (XmlUtils.nextElementWithin(parser, accountsDepth)) {
Tyler Gunn84253572014-09-02 14:50:05 -07001520 PhoneAccount account = sPhoneAccountXml.readFromXml(parser,
1521 s.versionNumber, context);
1522
1523 if (account != null && s.accounts != null) {
Ihab Awadb78b2762014-07-25 15:16:23 -07001524 s.accounts.add(account);
1525 }
1526 }
Ihab Awad104f8062014-07-17 11:29:35 -07001527 }
1528 }
Ihab Awadb78b2762014-07-25 15:16:23 -07001529 return s;
Ihab Awad104f8062014-07-17 11:29:35 -07001530 }
Ihab Awadb78b2762014-07-25 15:16:23 -07001531 return null;
Ihab Awad104f8062014-07-17 11:29:35 -07001532 }
1533 };
1534
Ihab Awadb78b2762014-07-25 15:16:23 -07001535 @VisibleForTesting
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001536 public static final XmlSerialization<DefaultPhoneAccountHandle> sDefaultPhoneAcountHandleXml =
1537 new XmlSerialization<DefaultPhoneAccountHandle>() {
1538 private static final String CLASS_DEFAULT_OUTGOING_PHONE_ACCOUNT_HANDLE
1539 = "default_outgoing_phone_account_handle";
1540 private static final String USER_SERIAL_NUMBER = "user_serial_number";
Brad Ebinger0c87b3c2016-06-10 17:23:02 -07001541 private static final String GROUP_ID = "group_id";
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001542 private static final String ACCOUNT_HANDLE = "account_handle";
1543
1544 @Override
1545 public void writeToXml(DefaultPhoneAccountHandle o, XmlSerializer serializer,
1546 Context context) throws IOException {
1547 if (o != null) {
1548 final UserManager userManager = UserManager.get(context);
1549 final long serialNumber = userManager.getSerialNumberForUser(o.userHandle);
1550 if (serialNumber != -1) {
1551 serializer.startTag(null, CLASS_DEFAULT_OUTGOING_PHONE_ACCOUNT_HANDLE);
1552 writeLong(USER_SERIAL_NUMBER, serialNumber, serializer);
Brad Ebinger0c87b3c2016-06-10 17:23:02 -07001553 writeNonNullString(GROUP_ID, o.groupId, serializer);
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001554 serializer.startTag(null, ACCOUNT_HANDLE);
1555 sPhoneAccountHandleXml.writeToXml(o.phoneAccountHandle, serializer,
1556 context);
1557 serializer.endTag(null, ACCOUNT_HANDLE);
1558 serializer.endTag(null, CLASS_DEFAULT_OUTGOING_PHONE_ACCOUNT_HANDLE);
1559 }
1560 }
1561 }
1562
1563 @Override
1564 public DefaultPhoneAccountHandle readFromXml(XmlPullParser parser, int version,
1565 Context context)
1566 throws IOException, XmlPullParserException {
1567 if (parser.getName().equals(CLASS_DEFAULT_OUTGOING_PHONE_ACCOUNT_HANDLE)) {
1568 int outerDepth = parser.getDepth();
1569 PhoneAccountHandle accountHandle = null;
1570 String userSerialNumberString = null;
Brad Ebinger0c87b3c2016-06-10 17:23:02 -07001571 String groupId = "";
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001572 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1573 if (parser.getName().equals(ACCOUNT_HANDLE)) {
1574 parser.nextTag();
1575 accountHandle = sPhoneAccountHandleXml.readFromXml(parser, version,
1576 context);
1577 } else if (parser.getName().equals(USER_SERIAL_NUMBER)) {
1578 parser.next();
1579 userSerialNumberString = parser.getText();
Brad Ebinger0c87b3c2016-06-10 17:23:02 -07001580 } else if (parser.getName().equals(GROUP_ID)) {
Hall Liuded880c2017-01-20 16:13:07 -08001581 if (parser.next() == XmlPullParser.TEXT) {
1582 groupId = parser.getText();
1583 }
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001584 }
1585 }
1586 UserHandle userHandle = null;
1587 if (userSerialNumberString != null) {
1588 try {
1589 long serialNumber = Long.parseLong(userSerialNumberString);
1590 userHandle = UserManager.get(context)
1591 .getUserForSerialNumber(serialNumber);
1592 } catch (NumberFormatException e) {
1593 Log.e(this, e,
1594 "Could not parse UserHandle " + userSerialNumberString);
1595 }
1596 }
Brad Ebinger0c87b3c2016-06-10 17:23:02 -07001597 if (accountHandle != null && userHandle != null && groupId != null) {
1598 return new DefaultPhoneAccountHandle(userHandle, accountHandle,
1599 groupId);
Tony Mak4a3e2fd2015-12-04 11:58:38 +00001600 }
1601 }
1602 return null;
1603 }
1604 };
1605
1606
1607 @VisibleForTesting
Ihab Awadb78b2762014-07-25 15:16:23 -07001608 public static final XmlSerialization<PhoneAccount> sPhoneAccountXml =
1609 new XmlSerialization<PhoneAccount>() {
1610 private static final String CLASS_PHONE_ACCOUNT = "phone_account";
1611 private static final String ACCOUNT_HANDLE = "account_handle";
Andrew Lee7129f1c2014-09-04 11:55:07 -07001612 private static final String ADDRESS = "handle";
1613 private static final String SUBSCRIPTION_ADDRESS = "subscription_number";
Ihab Awad104f8062014-07-17 11:29:35 -07001614 private static final String CAPABILITIES = "capabilities";
Christine Hallstromffe558c2016-11-30 16:05:13 -08001615 private static final String SUPPORTED_AUDIO_ROUTES = "supported_audio_routes";
Ihab Awad104f8062014-07-17 11:29:35 -07001616 private static final String ICON_RES_ID = "icon_res_id";
Ihab Awadd9f54382014-10-24 11:44:47 -07001617 private static final String ICON_PACKAGE_NAME = "icon_package_name";
1618 private static final String ICON_BITMAP = "icon_bitmap";
Ihab Awad7e2c7f32014-11-03 09:49:45 -08001619 private static final String ICON_TINT = "icon_tint";
1620 private static final String HIGHLIGHT_COLOR = "highlight_color";
Ihab Awad104f8062014-07-17 11:29:35 -07001621 private static final String LABEL = "label";
1622 private static final String SHORT_DESCRIPTION = "short_description";
Tyler Gunn84253572014-09-02 14:50:05 -07001623 private static final String SUPPORTED_URI_SCHEMES = "supported_uri_schemes";
Santos Cordon9c30c282015-05-13 16:28:27 -07001624 private static final String ICON = "icon";
Tyler Gunn369c8742015-10-07 15:39:28 -07001625 private static final String EXTRAS = "extras";
Santos Cordonea5cb932015-05-07 16:28:38 -07001626 private static final String ENABLED = "enabled";
Ihab Awad104f8062014-07-17 11:29:35 -07001627
1628 @Override
Evan Charlton105d9772014-11-25 14:08:53 -08001629 public void writeToXml(PhoneAccount o, XmlSerializer serializer, Context context)
Ihab Awadb78b2762014-07-25 15:16:23 -07001630 throws IOException {
Ihab Awad26923222014-07-30 10:54:35 -07001631 if (o != null) {
1632 serializer.startTag(null, CLASS_PHONE_ACCOUNT);
Ihab Awadb78b2762014-07-25 15:16:23 -07001633
Ihab Awad26923222014-07-30 10:54:35 -07001634 if (o.getAccountHandle() != null) {
1635 serializer.startTag(null, ACCOUNT_HANDLE);
Evan Charlton105d9772014-11-25 14:08:53 -08001636 sPhoneAccountHandleXml.writeToXml(o.getAccountHandle(), serializer, context);
Ihab Awad26923222014-07-30 10:54:35 -07001637 serializer.endTag(null, ACCOUNT_HANDLE);
1638 }
Ihab Awadb78b2762014-07-25 15:16:23 -07001639
Ihab Awadd9f54382014-10-24 11:44:47 -07001640 writeTextIfNonNull(ADDRESS, o.getAddress(), serializer);
1641 writeTextIfNonNull(SUBSCRIPTION_ADDRESS, o.getSubscriptionAddress(), serializer);
1642 writeTextIfNonNull(CAPABILITIES, Integer.toString(o.getCapabilities()), serializer);
Santos Cordon9c30c282015-05-13 16:28:27 -07001643 writeIconIfNonNull(ICON, o.getIcon(), serializer);
Ihab Awad7e2c7f32014-11-03 09:49:45 -08001644 writeTextIfNonNull(HIGHLIGHT_COLOR,
1645 Integer.toString(o.getHighlightColor()), serializer);
Ihab Awadd9f54382014-10-24 11:44:47 -07001646 writeTextIfNonNull(LABEL, o.getLabel(), serializer);
1647 writeTextIfNonNull(SHORT_DESCRIPTION, o.getShortDescription(), serializer);
Tyler Gunn84253572014-09-02 14:50:05 -07001648 writeStringList(SUPPORTED_URI_SCHEMES, o.getSupportedUriSchemes(), serializer);
Tyler Gunn369c8742015-10-07 15:39:28 -07001649 writeBundle(EXTRAS, o.getExtras(), serializer);
Santos Cordonea5cb932015-05-07 16:28:38 -07001650 writeTextIfNonNull(ENABLED, o.isEnabled() ? "true" : "false" , serializer);
Christine Hallstromffe558c2016-11-30 16:05:13 -08001651 writeTextIfNonNull(SUPPORTED_AUDIO_ROUTES, Integer.toString(
1652 o.getSupportedAudioRoutes()), serializer);
Ihab Awadb78b2762014-07-25 15:16:23 -07001653
Ihab Awad26923222014-07-30 10:54:35 -07001654 serializer.endTag(null, CLASS_PHONE_ACCOUNT);
1655 }
Ihab Awad104f8062014-07-17 11:29:35 -07001656 }
1657
Tyler Gunn84253572014-09-02 14:50:05 -07001658 public PhoneAccount readFromXml(XmlPullParser parser, int version, Context context)
Ihab Awadb78b2762014-07-25 15:16:23 -07001659 throws IOException, XmlPullParserException {
1660 if (parser.getName().equals(CLASS_PHONE_ACCOUNT)) {
1661 int outerDepth = parser.getDepth();
1662 PhoneAccountHandle accountHandle = null;
Andrew Lee7129f1c2014-09-04 11:55:07 -07001663 Uri address = null;
1664 Uri subscriptionAddress = null;
Ihab Awadb78b2762014-07-25 15:16:23 -07001665 int capabilities = 0;
Christine Hallstromffe558c2016-11-30 16:05:13 -08001666 int supportedAudioRoutes = 0;
Ihab Awad7e2c7f32014-11-03 09:49:45 -08001667 int iconResId = PhoneAccount.NO_RESOURCE_ID;
Ihab Awadd9f54382014-10-24 11:44:47 -07001668 String iconPackageName = null;
Ihab Awad7e2c7f32014-11-03 09:49:45 -08001669 Bitmap iconBitmap = null;
Ihab Awad07bc5ee2014-11-12 13:42:52 -08001670 int iconTint = PhoneAccount.NO_ICON_TINT;
1671 int highlightColor = PhoneAccount.NO_HIGHLIGHT_COLOR;
Ihab Awadb78b2762014-07-25 15:16:23 -07001672 String label = null;
1673 String shortDescription = null;
Tyler Gunn84253572014-09-02 14:50:05 -07001674 List<String> supportedUriSchemes = null;
Santos Cordon9c30c282015-05-13 16:28:27 -07001675 Icon icon = null;
Santos Cordonea5cb932015-05-07 16:28:38 -07001676 boolean enabled = false;
Tyler Gunn369c8742015-10-07 15:39:28 -07001677 Bundle extras = null;
Ihab Awadb78b2762014-07-25 15:16:23 -07001678
1679 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1680 if (parser.getName().equals(ACCOUNT_HANDLE)) {
1681 parser.nextTag();
Tyler Gunn84253572014-09-02 14:50:05 -07001682 accountHandle = sPhoneAccountHandleXml.readFromXml(parser, version,
1683 context);
Andrew Lee7129f1c2014-09-04 11:55:07 -07001684 } else if (parser.getName().equals(ADDRESS)) {
Ihab Awadb78b2762014-07-25 15:16:23 -07001685 parser.next();
Andrew Lee7129f1c2014-09-04 11:55:07 -07001686 address = Uri.parse(parser.getText());
1687 } else if (parser.getName().equals(SUBSCRIPTION_ADDRESS)) {
Ihab Awadb78b2762014-07-25 15:16:23 -07001688 parser.next();
Andrew Lee7129f1c2014-09-04 11:55:07 -07001689 String nextText = parser.getText();
1690 subscriptionAddress = nextText == null ? null : Uri.parse(nextText);
Ihab Awadb78b2762014-07-25 15:16:23 -07001691 } else if (parser.getName().equals(CAPABILITIES)) {
1692 parser.next();
1693 capabilities = Integer.parseInt(parser.getText());
1694 } else if (parser.getName().equals(ICON_RES_ID)) {
1695 parser.next();
1696 iconResId = Integer.parseInt(parser.getText());
Ihab Awadd9f54382014-10-24 11:44:47 -07001697 } else if (parser.getName().equals(ICON_PACKAGE_NAME)) {
1698 parser.next();
1699 iconPackageName = parser.getText();
1700 } else if (parser.getName().equals(ICON_BITMAP)) {
1701 parser.next();
Ihab Awad7e2c7f32014-11-03 09:49:45 -08001702 iconBitmap = readBitmap(parser);
1703 } else if (parser.getName().equals(ICON_TINT)) {
Nancy Chen06ce0622014-10-23 01:17:35 +00001704 parser.next();
Ihab Awad7e2c7f32014-11-03 09:49:45 -08001705 iconTint = Integer.parseInt(parser.getText());
1706 } else if (parser.getName().equals(HIGHLIGHT_COLOR)) {
1707 parser.next();
1708 highlightColor = Integer.parseInt(parser.getText());
Ihab Awadb78b2762014-07-25 15:16:23 -07001709 } else if (parser.getName().equals(LABEL)) {
1710 parser.next();
1711 label = parser.getText();
1712 } else if (parser.getName().equals(SHORT_DESCRIPTION)) {
1713 parser.next();
1714 shortDescription = parser.getText();
Tyler Gunn84253572014-09-02 14:50:05 -07001715 } else if (parser.getName().equals(SUPPORTED_URI_SCHEMES)) {
1716 supportedUriSchemes = readStringList(parser);
Santos Cordon9c30c282015-05-13 16:28:27 -07001717 } else if (parser.getName().equals(ICON)) {
1718 parser.next();
1719 icon = readIcon(parser);
Santos Cordonea5cb932015-05-07 16:28:38 -07001720 } else if (parser.getName().equals(ENABLED)) {
1721 parser.next();
1722 enabled = "true".equalsIgnoreCase(parser.getText());
Tyler Gunn369c8742015-10-07 15:39:28 -07001723 } else if (parser.getName().equals(EXTRAS)) {
Tyler Gunn369c8742015-10-07 15:39:28 -07001724 extras = readBundle(parser);
Christine Hallstromffe558c2016-11-30 16:05:13 -08001725 } else if (parser.getName().equals(SUPPORTED_AUDIO_ROUTES)) {
1726 parser.next();
1727 supportedAudioRoutes = Integer.parseInt(parser.getText());
Ihab Awadb78b2762014-07-25 15:16:23 -07001728 }
1729 }
Tyler Gunn84253572014-09-02 14:50:05 -07001730
Santos Cordona9eebe42015-06-11 14:07:44 -07001731 ComponentName pstnComponentName = new ComponentName("com.android.phone",
1732 "com.android.services.telephony.TelephonyConnectionService");
Santos Cordona82aed82015-05-26 10:43:56 -07001733 ComponentName sipComponentName = new ComponentName("com.android.phone",
1734 "com.android.services.telephony.sip.SipConnectionService");
1735
Tyler Gunn84253572014-09-02 14:50:05 -07001736 // Upgrade older phone accounts to specify the supported URI schemes.
1737 if (version < 2) {
Tyler Gunn84253572014-09-02 14:50:05 -07001738 supportedUriSchemes = new ArrayList<>();
1739
1740 // Handle the SIP connection service.
1741 // Check the system settings to see if it also should handle "tel" calls.
1742 if (accountHandle.getComponentName().equals(sipComponentName)) {
1743 boolean useSipForPstn = useSipForPstnCalls(context);
1744 supportedUriSchemes.add(PhoneAccount.SCHEME_SIP);
1745 if (useSipForPstn) {
1746 supportedUriSchemes.add(PhoneAccount.SCHEME_TEL);
1747 }
1748 } else {
1749 supportedUriSchemes.add(PhoneAccount.SCHEME_TEL);
1750 supportedUriSchemes.add(PhoneAccount.SCHEME_VOICEMAIL);
1751 }
1752 }
1753
Ihab Awad7e2c7f32014-11-03 09:49:45 -08001754 // Upgrade older phone accounts with explicit package name
1755 if (version < 5) {
1756 if (iconBitmap == null) {
1757 iconPackageName = accountHandle.getComponentName().getPackageName();
1758 }
1759 }
1760
Santos Cordona82aed82015-05-26 10:43:56 -07001761 if (version < 6) {
1762 // Always enable all SIP accounts on upgrade to version 6
1763 if (accountHandle.getComponentName().equals(sipComponentName)) {
1764 enabled = true;
1765 }
1766 }
Santos Cordona9eebe42015-06-11 14:07:44 -07001767 if (version < 7) {
1768 // Always enabled all PSTN acocunts on upgrade to version 7
1769 if (accountHandle.getComponentName().equals(pstnComponentName)) {
1770 enabled = true;
1771 }
1772 }
Roshan Pius6f752c82015-08-10 10:42:06 -07001773 if (version < 8) {
1774 // Migrate the SIP account handle ids to use SIP username instead of SIP URI.
1775 if (accountHandle.getComponentName().equals(sipComponentName)) {
1776 Uri accountUri = Uri.parse(accountHandle.getId());
1777 if (accountUri.getScheme() != null &&
1778 accountUri.getScheme().equals(PhoneAccount.SCHEME_SIP)) {
1779 accountHandle = new PhoneAccountHandle(accountHandle.getComponentName(),
1780 accountUri.getSchemeSpecificPart(),
1781 accountHandle.getUserHandle());
1782 }
1783 }
1784 }
Santos Cordona82aed82015-05-26 10:43:56 -07001785
Christine Hallstromffe558c2016-11-30 16:05:13 -08001786 if (version < 9) {
1787 // Set supported audio routes to all by default
1788 supportedAudioRoutes = CallAudioState.ROUTE_ALL;
1789 }
1790
Ihab Awad7e2c7f32014-11-03 09:49:45 -08001791 PhoneAccount.Builder builder = PhoneAccount.builder(accountHandle, label)
Andrew Lee7129f1c2014-09-04 11:55:07 -07001792 .setAddress(address)
1793 .setSubscriptionAddress(subscriptionAddress)
1794 .setCapabilities(capabilities)
Christine Hallstromffe558c2016-11-30 16:05:13 -08001795 .setSupportedAudioRoutes(supportedAudioRoutes)
Andrew Lee7129f1c2014-09-04 11:55:07 -07001796 .setShortDescription(shortDescription)
1797 .setSupportedUriSchemes(supportedUriSchemes)
Santos Cordonea5cb932015-05-07 16:28:38 -07001798 .setHighlightColor(highlightColor)
Tyler Gunn369c8742015-10-07 15:39:28 -07001799 .setExtras(extras)
Santos Cordonea5cb932015-05-07 16:28:38 -07001800 .setIsEnabled(enabled);
Ihab Awad7e2c7f32014-11-03 09:49:45 -08001801
Santos Cordon9c30c282015-05-13 16:28:27 -07001802 if (icon != null) {
1803 builder.setIcon(icon);
1804 } else if (iconBitmap != null) {
1805 builder.setIcon(Icon.createWithBitmap(iconBitmap));
1806 } else if (!TextUtils.isEmpty(iconPackageName)) {
1807 builder.setIcon(Icon.createWithResource(iconPackageName, iconResId));
1808 // TODO: Need to set tint.
Ihab Awad7e2c7f32014-11-03 09:49:45 -08001809 }
1810
Ihab Awad0a4b95f2015-05-18 10:15:38 -07001811 return builder.build();
Ihab Awadb78b2762014-07-25 15:16:23 -07001812 }
1813 return null;
Ihab Awad104f8062014-07-17 11:29:35 -07001814 }
Tyler Gunn84253572014-09-02 14:50:05 -07001815
1816 /**
Santos Cordon9c30c282015-05-13 16:28:27 -07001817 * Determines if the SIP call settings specify to use SIP for all calls, including PSTN
1818 * calls.
Tyler Gunn84253572014-09-02 14:50:05 -07001819 *
1820 * @param context The context.
1821 * @return {@code True} if SIP should be used for all calls.
1822 */
1823 private boolean useSipForPstnCalls(Context context) {
1824 String option = Settings.System.getString(context.getContentResolver(),
1825 Settings.System.SIP_CALL_OPTIONS);
1826 option = (option != null) ? option : Settings.System.SIP_ADDRESS_ONLY;
1827 return option.equals(Settings.System.SIP_ALWAYS);
1828 }
Ihab Awad104f8062014-07-17 11:29:35 -07001829 };
1830
Ihab Awadb78b2762014-07-25 15:16:23 -07001831 @VisibleForTesting
1832 public static final XmlSerialization<PhoneAccountHandle> sPhoneAccountHandleXml =
1833 new XmlSerialization<PhoneAccountHandle>() {
1834 private static final String CLASS_PHONE_ACCOUNT_HANDLE = "phone_account_handle";
Ihab Awad104f8062014-07-17 11:29:35 -07001835 private static final String COMPONENT_NAME = "component_name";
1836 private static final String ID = "id";
Evan Charlton105d9772014-11-25 14:08:53 -08001837 private static final String USER_SERIAL_NUMBER = "user_serial_number";
Ihab Awad104f8062014-07-17 11:29:35 -07001838
1839 @Override
Evan Charlton105d9772014-11-25 14:08:53 -08001840 public void writeToXml(PhoneAccountHandle o, XmlSerializer serializer, Context context)
Ihab Awadb78b2762014-07-25 15:16:23 -07001841 throws IOException {
Ihab Awad26923222014-07-30 10:54:35 -07001842 if (o != null) {
1843 serializer.startTag(null, CLASS_PHONE_ACCOUNT_HANDLE);
Ihab Awadb78b2762014-07-25 15:16:23 -07001844
Ihab Awad26923222014-07-30 10:54:35 -07001845 if (o.getComponentName() != null) {
Ihab Awadd9f54382014-10-24 11:44:47 -07001846 writeTextIfNonNull(
Ihab Awad26923222014-07-30 10:54:35 -07001847 COMPONENT_NAME, o.getComponentName().flattenToString(), serializer);
1848 }
Ihab Awadb78b2762014-07-25 15:16:23 -07001849
Ihab Awadd9f54382014-10-24 11:44:47 -07001850 writeTextIfNonNull(ID, o.getId(), serializer);
Ihab Awadb78b2762014-07-25 15:16:23 -07001851
Evan Charlton105d9772014-11-25 14:08:53 -08001852 if (o.getUserHandle() != null && context != null) {
1853 UserManager userManager = UserManager.get(context);
1854 writeLong(USER_SERIAL_NUMBER,
1855 userManager.getSerialNumberForUser(o.getUserHandle()), serializer);
1856 }
1857
Ihab Awad26923222014-07-30 10:54:35 -07001858 serializer.endTag(null, CLASS_PHONE_ACCOUNT_HANDLE);
1859 }
Ihab Awad104f8062014-07-17 11:29:35 -07001860 }
1861
1862 @Override
Tyler Gunn84253572014-09-02 14:50:05 -07001863 public PhoneAccountHandle readFromXml(XmlPullParser parser, int version, Context context)
Ihab Awadb78b2762014-07-25 15:16:23 -07001864 throws IOException, XmlPullParserException {
1865 if (parser.getName().equals(CLASS_PHONE_ACCOUNT_HANDLE)) {
1866 String componentNameString = null;
1867 String idString = null;
Evan Charlton105d9772014-11-25 14:08:53 -08001868 String userSerialNumberString = null;
Ihab Awadb78b2762014-07-25 15:16:23 -07001869 int outerDepth = parser.getDepth();
Evan Charlton105d9772014-11-25 14:08:53 -08001870
1871 UserManager userManager = UserManager.get(context);
1872
Ihab Awadb78b2762014-07-25 15:16:23 -07001873 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1874 if (parser.getName().equals(COMPONENT_NAME)) {
1875 parser.next();
1876 componentNameString = parser.getText();
1877 } else if (parser.getName().equals(ID)) {
1878 parser.next();
1879 idString = parser.getText();
Evan Charlton105d9772014-11-25 14:08:53 -08001880 } else if (parser.getName().equals(USER_SERIAL_NUMBER)) {
1881 parser.next();
1882 userSerialNumberString = parser.getText();
Ihab Awadb78b2762014-07-25 15:16:23 -07001883 }
1884 }
Ihab Awad26923222014-07-30 10:54:35 -07001885 if (componentNameString != null) {
Evan Charlton105d9772014-11-25 14:08:53 -08001886 UserHandle userHandle = null;
1887 if (userSerialNumberString != null) {
1888 try {
1889 long serialNumber = Long.parseLong(userSerialNumberString);
1890 userHandle = userManager.getUserForSerialNumber(serialNumber);
1891 } catch (NumberFormatException e) {
1892 Log.e(this, e, "Could not parse UserHandle " + userSerialNumberString);
1893 }
1894 }
Ihab Awadb78b2762014-07-25 15:16:23 -07001895 return new PhoneAccountHandle(
1896 ComponentName.unflattenFromString(componentNameString),
Evan Charlton105d9772014-11-25 14:08:53 -08001897 idString,
1898 userHandle);
Ihab Awadb78b2762014-07-25 15:16:23 -07001899 }
1900 }
1901 return null;
Ihab Awad104f8062014-07-17 11:29:35 -07001902 }
1903 };
Srikanth Chintalad5d2dd92016-06-23 16:02:33 +05301904
1905 private String nullToEmpty(String str) {
1906 return str == null ? "" : str;
1907 }
Santos Cordon176ae282014-07-14 02:02:14 -07001908}