1 /* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License 15 */ 16 package com.android.providers.blockednumber; 17 18 import android.annotation.NonNull; 19 import android.annotation.Nullable; 20 import android.content.Context; 21 import android.location.Country; 22 import android.location.CountryDetector; 23 import android.telephony.PhoneNumberUtils; 24 import android.text.TextUtils; 25 26 import java.util.Locale; 27 28 public class Utils { 29 private Utils() { 30 } 31 32 public static final int MIN_INDEX_LEN = 8; 33 34 /** 35 * @return The current country code. 36 */ 37 public static @NonNull String getCurrentCountryIso(@NonNull Context context) { 38 final CountryDetector detector = (CountryDetector) context.getSystemService( 39 Context.COUNTRY_DETECTOR); 40 if (detector != null) { 41 final Country country = detector.detectCountry(); 42 if (country != null) { 43 return country.getCountryIso(); 44 } 45 } 46 final Locale locale = context.getResources().getConfiguration().locale; 47 return locale.getCountry(); 48 } 49 50 /** 51 * Converts a phone number to an E164 number, assuming the current country. If {@code 52 * incomingE16Number} is provided, it'll just strip it and returns. If the number is not valid, 53 * it'll return "". 54 * 55 * <p>Special case: if {@code rawNumber} contains '@', it's considered as an email address and 56 * returned unmodified. 57 */ 58 public static @NonNull String getE164Number(@NonNull Context context, 59 @Nullable String rawNumber, @Nullable String incomingE16Number) { 60 if (rawNumber != null && rawNumber.contains("@")) { 61 return rawNumber; 62 } 63 if (!TextUtils.isEmpty(incomingE16Number)) { 64 return incomingE16Number; 65 } 66 if (TextUtils.isEmpty(rawNumber)) { 67 return ""; 68 } 69 final String e164 = 70 PhoneNumberUtils.formatNumberToE164(rawNumber, getCurrentCountryIso(context)); 71 return e164 == null ? "" : e164; 72 } 73 74 public static @Nullable String wrapSelectionWithParens(@Nullable String selection) { 75 return TextUtils.isEmpty(selection) ? null : "(" + selection + ")"; 76 } 77 } 78