1 /*
2  * Copyright (C) 2021 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.settings.deviceinfo;
17 
18 import android.text.Spannable;
19 import android.text.SpannableStringBuilder;
20 import android.text.Spanned;
21 import android.text.TextUtils;
22 import android.text.style.TtsSpan;
23 
24 import java.util.Arrays;
25 import java.util.stream.IntStream;
26 
27 /**
28  * Helper class to detect format of phone number.
29  */
30 public class PhoneNumberUtil {
31 
32     /**
33      * Convert given text to support phone number talkback.
34      * @param text given
35      * @return converted text
36      */
expandByTts(CharSequence text)37     public static CharSequence expandByTts(CharSequence text) {
38         if ((text == null) || (text.length() <= 0)
39             || (!isPhoneNumberDigits(text))) {
40             return text;
41         }
42         Spannable spannable = new SpannableStringBuilder(text);
43         TtsSpan span = new TtsSpan.DigitsBuilder(text.toString()).build();
44         spannable.setSpan(span, 0, spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
45         return spannable;
46     }
47 
48     /**
49      * Check if given text may contains a phone id related numbers.
50      * (ex: phone number, IMEI, ICCID)
51      * @param text given
52      * @return true when given text is a phone id related number.
53      */
isPhoneNumberDigits(CharSequence text)54     private static boolean isPhoneNumberDigits(CharSequence text) {
55         long textLength = (long)text.length();
56         return (textLength == text.chars()
57                 .filter(c -> isPhoneNumberDigit(c)).count());
58     }
59 
isPhoneNumberDigit(int c)60     private static boolean isPhoneNumberDigit(int c) {
61         return ((c >= (int)'0') && (c <= (int)'9'))
62             || (c == (int)'-') || (c == (int)'+')
63             || (c == (int)'(') || (c == (int)')');
64     }
65 }
66