blob: 77e02b40a909eddf12f300ff90107fb6f853dff3 [file] [log] [blame]
Bonian Chend051e652021-12-03 00:05:00 +08001/*
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 */
16package com.android.settings.deviceinfo;
17
18import android.text.Spannable;
19import android.text.SpannableStringBuilder;
20import android.text.Spanned;
21import android.text.TextUtils;
22import android.text.style.TtsSpan;
23
24import java.util.Arrays;
25import java.util.stream.IntStream;
26
27/**
28 * Helper class to detect format of phone number.
29 */
30public class PhoneNumberUtil {
31
32 /**
33 * Convert given text to support phone number talkback.
34 * @param text given
35 * @return converted text
36 */
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 */
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
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}