summaryrefslogtreecommitdiffstats
path: root/src/com/android/contacts/common/MoreContactUtils.java
blob: 8f465ad4e4d2c9c129f934b23234594ef25e7251 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
/*
 * Copyright (C) 2013-2015, The Linux Foundation. All Rights Reserved.
 * Not a Contribution.
 *
 * Copyright (C) 2012 The Android Open Source Project
 *
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

package com.android.contacts.common;

import android.accounts.Account;

import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.graphics.Rect;
import android.net.Uri;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemProperties;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.provider.Settings;
import android.telephony.SubscriptionManager;
import android.telecom.PhoneAccountHandle;
import android.telephony.TelephonyManager;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.internal.telephony.PhoneConstants;
import com.android.contacts.common.model.account.AccountType;
import com.android.contacts.common.model.account.SimAccountType;
import com.android.internal.telephony.uicc.AdnRecord;
import com.android.internal.telephony.uicc.IccConstants;
import com.android.internal.telephony.IIccPhoneBook;

import java.util.ArrayList;
import java.util.List;

/**
 * Shared static contact utility methods.
 */
public class MoreContactUtils {

    private static final String WAIT_SYMBOL_AS_STRING = String.valueOf(PhoneNumberUtils.WAIT);
    private static final boolean DBG = true;
    private static final String TAG = "MoreContactUtils";
    public static final int MAX_LENGTH_NAME_IN_SIM = 14;
    public static final int MAX_LENGTH_NAME_WITH_CHINESE_IN_SIM = 6;
    public static final int MAX_LENGTH_NUMBER_IN_SIM = 20;
    public static final int MAX_LENGTH_EMAIL_IN_SIM = 40;
    private static final int NAME_POS = 0;
    private static final int NUMBER_POS = 1;
    private static final int EMAIL_POS = 2;
    private static final int ANR_POS = 3;
    private static final String PHONEBOOK = "simphonebook";
    public static final String[] MULTI_SIM_NAME = { "perferred_name_sub1",
            "perferred_name_sub2" };

    public static final String PREFERRED_SIM_ICON_INDEX = "preferred_sim_icon_index";
    public static final String[] IPCALL_PREFIX = { "ipcall_prefix1",
            "ipcall_prefix2" };
    public final static int[] IC_SIM_PICTURE = {
        R.drawable.ic_contact_picture_sim_1,
        R.drawable.ic_contact_picture_sim_2,
        R.drawable.ic_contact_picture_sim_personal,
        R.drawable.ic_contact_picture_sim_business,
        R.drawable.ic_contact_picture_sim_primary
    };
    /**
     * Returns true if two data with mimetypes which represent values in contact entries are
     * considered equal for collapsing in the GUI. For caller-id, use
     * {@link android.telephony.PhoneNumberUtils#compare(android.content.Context, String, String)}
     * instead
     */
    public static boolean shouldCollapse(CharSequence mimetype1, CharSequence data1,
              CharSequence mimetype2, CharSequence data2) {
        // different mimetypes? don't collapse
        if (!TextUtils.equals(mimetype1, mimetype2)) return false;

        // exact same string? good, bail out early
        if (TextUtils.equals(data1, data2)) return true;

        // so if either is null, these two must be different
        if (data1 == null || data2 == null) return false;

        // if this is not about phone numbers, we know this is not a match (of course, some
        // mimetypes could have more sophisticated matching is the future, e.g. addresses)
        if (!TextUtils.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
                mimetype1)) {
            return false;
        }

        return shouldCollapsePhoneNumbers(data1.toString(), data2.toString());
    }

    // TODO: Move this to PhoneDataItem.shouldCollapse override
    private static boolean shouldCollapsePhoneNumbers(String number1, String number2) {
        // Work around to address b/20724444. We want to distinguish between #555, *555 and 555.
        // This makes no attempt to distinguish between 555 and 55*5, since 55*5 is an improbable
        // number. PhoneNumberUtil already distinguishes between 555 and 55#5.
        if (number1.contains("#") != number2.contains("#")
                || number1.contains("*") != number2.contains("*")) {
            return false;
        }

        // Now do the full phone number thing. split into parts, separated by waiting symbol
        // and compare them individually
        final String[] dataParts1 = number1.split(WAIT_SYMBOL_AS_STRING);
        final String[] dataParts2 = number2.split(WAIT_SYMBOL_AS_STRING);
        if (dataParts1.length != dataParts2.length) return false;
        final PhoneNumberUtil util = PhoneNumberUtil.getInstance();
        for (int i = 0; i < dataParts1.length; i++) {
            // Match phone numbers represented by keypad letters, in which case prefer the
            // phone number with letters.
            final String dataPart1 = PhoneNumberUtils.convertKeypadLettersToDigits(dataParts1[i]);
            final String dataPart2 = dataParts2[i];

            // substrings equal? shortcut, don't parse
            if (TextUtils.equals(dataPart1, dataPart2)) continue;

            // do a full parse of the numbers
            final PhoneNumberUtil.MatchType result = util.isNumberMatch(dataPart1, dataPart2);
            switch (result) {
                case NOT_A_NUMBER:
                    // don't understand the numbers? let's play it safe
                    return false;
                case NO_MATCH:
                    return false;
                case EXACT_MATCH:
                    break;
                case NSN_MATCH:
                    try {
                        // For NANP phone numbers, match when one has +1 and the other does not.
                        // In this case, prefer the +1 version.
                        if (util.parse(dataPart1, null).getCountryCode() == 1) {
                            // At this point, the numbers can be either case 1 or 2 below....
                            //
                            // case 1)
                            // +14155551212    <--- country code 1
                            //  14155551212    <--- 1 is trunk prefix, not country code
                            //
                            // and
                            //
                            // case 2)
                            // +14155551212
                            //   4155551212
                            //
                            // From b/7519057, case 2 needs to be equal.  But also that bug, case 3
                            // below should not be equal.
                            //
                            // case 3)
                            // 14155551212
                            //  4155551212
                            //
                            // So in order to make sure transitive equality is valid, case 1 cannot
                            // be equal.  Otherwise, transitive equality breaks and the following
                            // would all be collapsed:
                            //   4155551212  |
                            //  14155551212  |---->   +14155551212
                            // +14155551212  |
                            //
                            // With transitive equality, the collapsed values should be:
                            //   4155551212  |         14155551212
                            //  14155551212  |---->   +14155551212
                            // +14155551212  |

                            // Distinguish between case 1 and 2 by checking for trunk prefix '1'
                            // at the start of number 2.
                            if (dataPart2.trim().charAt(0) == '1') {
                                // case 1
                                return false;
                            }
                            break;
                        }
                    } catch (NumberParseException e) {
                        // This is the case where the first number does not have a country code.
                        // examples:
                        // (123) 456-7890   &   123-456-7890  (collapse)
                        // 0049 (8092) 1234   &   +49/80921234  (unit test says do not collapse)

                        // Check the second number.  If it also does not have a country code, then
                        // we should collapse.  If it has a country code, then it's a different
                        // number and we should not collapse (this conclusion is based on an
                        // existing unit test).
                        try {
                            util.parse(dataPart2, null);
                        } catch (NumberParseException e2) {
                            // Number 2 also does not have a country.  Collapse.
                            break;
                        }
                    }
                    return false;
                case SHORT_NSN_MATCH:
                    return false;
                default:
                    throw new IllegalStateException("Unknown result value from phone number " +
                            "library");
            }
        }
        return true;
    }

    /**
     * Returns the {@link android.graphics.Rect} with left, top, right, and bottom coordinates
     * that are equivalent to the given {@link android.view.View}'s bounds. This is equivalent to
     * how the target {@link android.graphics.Rect} is calculated in
     * {@link android.provider.ContactsContract.QuickContact#showQuickContact}.
     */
    public static Rect getTargetRectFromView(View view) {
        final int[] pos = new int[2];
        view.getLocationOnScreen(pos);

        final Rect rect = new Rect();
        rect.left = pos[0];
        rect.top = pos[1];
        rect.right = pos[0] + view.getWidth();
        rect.bottom = pos[1] + view.getHeight();
        return rect;
    }

    /**
     * Returns a header view based on the R.layout.list_separator, where the
     * containing {@link android.widget.TextView} is set using the given textResourceId.
     */
    public static TextView createHeaderView(Context context, int textResourceId) {
        final TextView textView = (TextView) View.inflate(context, R.layout.list_separator, null);
        textView.setText(context.getString(textResourceId));
        return textView;
    }

    /**
     * Set the top padding on the header view dynamically, based on whether the header is in
     * the first row or not.
     */
    public static void setHeaderViewBottomPadding(Context context, TextView textView,
            boolean isFirstRow) {
        final int topPadding;
        if (isFirstRow) {
            topPadding = (int) context.getResources().getDimension(
                    R.dimen.frequently_contacted_title_top_margin_when_first_row);
        } else {
            topPadding = (int) context.getResources().getDimension(
                    R.dimen.frequently_contacted_title_top_margin);
        }
        textView.setPaddingRelative(textView.getPaddingStart(), topPadding,
                textView.getPaddingEnd(), textView.getPaddingBottom());
    }


    /**
     * Returns the intent to launch for the given invitable account type and contact lookup URI.
     * This will return null if the account type is not invitable (i.e. there is no
     * {@link AccountType#getInviteContactActivityClassName()} or
     * {@link AccountType#syncAdapterPackageName}).
     */
    public static Intent getInvitableIntent(AccountType accountType, Uri lookupUri) {
        String syncAdapterPackageName = accountType.syncAdapterPackageName;
        String className = accountType.getInviteContactActivityClassName();
        if (TextUtils.isEmpty(syncAdapterPackageName) || TextUtils.isEmpty(className)) {
            return null;
        }
        Intent intent = new Intent();
        intent.setClassName(syncAdapterPackageName, className);

        intent.setAction(ContactsContract.Intents.INVITE_CONTACT);

        // Data is the lookup URI.
        intent.setData(lookupUri);
        return intent;
    }

    /** get disabled SIM card's name */
    public static String getDisabledSimFilter() {
        int count = TelephonyManager.getDefault().getPhoneCount();
        StringBuilder simFilter = new StringBuilder("");

        for (int i = 0; i < count; i++) {
            if (TelephonyManager.SIM_STATE_UNKNOWN == TelephonyManager
                    .getDefault().getSimState(i)) {
                simFilter.append(getSimAccountName(i) + ',');
            }
        }

        return simFilter.toString();
    }

    public static boolean isAPMOnAndSIMPowerDown(Context context) {
        if (context == null) {
            return false;
        }
        boolean isAirPlaneMode = Settings.System.getInt(context.getContentResolver(),
                Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
        boolean isSIMPowerDown = SystemProperties.getInt(
                "persist.radio.apm_sim_not_pwdn", 0) == 0;
        return isAirPlaneMode && isSIMPowerDown;
    }

    /**
     * Get SIM card account name
     */
    public static String getSimAccountName(int subscription) {
        if (TelephonyManager.getDefault().isMultiSimEnabled()) {
            return SimContactsConstants.SIM_NAME + (subscription + 1);
        } else {
            return SimContactsConstants.SIM_NAME;
        }
    }

    public static int getSubscription(String accountType, String accountName) {
        int subscription = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
        if (accountType == null || accountName == null)
            return subscription;
        if (accountType.equals(SimContactsConstants.ACCOUNT_TYPE_SIM)) {
            if (accountName.equals(SimContactsConstants.SIM_NAME)
                    || accountName.equals(SimContactsConstants.SIM_NAME_1)) {
                subscription = PhoneConstants.SUB1;
            } else if (accountName.equals(SimContactsConstants.SIM_NAME_2)) {
                subscription = PhoneConstants.SUB2;
            }
        }
        return subscription;
    }

    public static int getAnrCount(int slot) {
        int anrCount = 0;
        int[] subId = SubscriptionManager.getSubId(slot);
        try {
            IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(
                ServiceManager.getService("simphonebook"));

            if (iccIpb != null) {
                if (subId != null
                        && TelephonyManager.getDefault().isMultiSimEnabled()) {
                    anrCount = iccIpb.getAnrCountUsingSubId(subId[0]);
                } else {
                    anrCount = iccIpb.getAnrCount();
                }
            }
        } catch (RemoteException ex) {
            // ignore it
        }

        return anrCount;
    }

    public static int getAdnCount(int slot) {
        int adnCount = 0;
        int[] subId = SubscriptionManager.getSubId(slot);
                try {
            IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(
                ServiceManager.getService("simphonebook"));
            if (iccIpb != null) {
                if (subId != null
                        && TelephonyManager.getDefault().isMultiSimEnabled()) {
                    adnCount = iccIpb.getAdnCountUsingSubId(subId[0]);
                } else {
                    adnCount = iccIpb.getAdnCount();
                }
            }
        } catch (RemoteException ex) {
            // ignore it
        }
        return adnCount;
    }

    public static int getEmailCount(int slot) {
        int emailCount = 0;
        int[] subId = SubscriptionManager.getSubId(slot);
                try {
            IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(
                ServiceManager.getService("simphonebook"));

            if (iccIpb != null) {
                if (subId != null
                        && TelephonyManager.getDefault().isMultiSimEnabled()) {
                    emailCount = iccIpb.getEmailCountUsingSubId(subId[0]);
                } else {
                    emailCount = iccIpb.getEmailCount();
                }
            }
        } catch (RemoteException ex) {
            // ignore it
        }

        return emailCount;
    }

    /**
     * Returns the subscription's card can save anr or not.
     */
    public static boolean canSaveAnr(int slot) {
        return getAnrCount(slot) > 0 ? true : false;
    }

    /**
     * Returns the subscription's card can save email or not.
     */
    public static boolean canSaveEmail(int subscription) {
        return getEmailCount(subscription) > 0 ? true : false;
    }

    public static int getOneSimAnrCount(int sub) {
        int count = 0;
        int anrCount = getAnrCount(sub);
        int adnCount = getAdnCount(sub);
        if (adnCount > 0) {
            count = anrCount % adnCount != 0 ? (anrCount / adnCount + 1)
                    : (anrCount / adnCount);
        }
        return count;
    }

    public static int getOneSimEmailCount(int sub) {
        int count = 0;
        int emailCount = getEmailCount(sub);
        int adnCount = getAdnCount(sub);
        if (adnCount > 0) {
            count = emailCount % adnCount != 0 ? (emailCount / adnCount + 1)
                    : (emailCount / adnCount);
        }
        return count;
    }

    public static boolean insertToPhone(String[] values, final ContentResolver resolver,int sub) {
        Account account = getAcount(sub);
        final String name = values[NAME_POS];
        final String phoneNumber = values[NUMBER_POS];
        final String emailAddresses = values[EMAIL_POS];
        final String anrs = values[ANR_POS];

        final String[] emailAddressArray;
        final String[] anrArray;
        boolean success = true;
        if (!TextUtils.isEmpty(emailAddresses)) {
            emailAddressArray = emailAddresses.split(",");
        } else {
            emailAddressArray = null;
        }
        if (!TextUtils.isEmpty(anrs)) {
            anrArray = anrs.split(SimContactsConstants.ANR_SEP);
        } else {
            anrArray = null;
        }
        if (DBG) {
            Log.d(TAG, "insertToPhone: name= " + name + ", phoneNumber= " + phoneNumber
                    + ", emails= " + emailAddresses + ", anrs= " + anrs + ", account= " + account);
        }
        final ArrayList<ContentProviderOperation> operationList =
                new ArrayList<ContentProviderOperation>();
        ContentProviderOperation.Builder builder = ContentProviderOperation
                .newInsert(RawContacts.CONTENT_URI);
        builder.withValue(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_DISABLED);

        if (account != null) {
            builder.withValue(RawContacts.ACCOUNT_NAME, account.name);
            builder.withValue(RawContacts.ACCOUNT_TYPE, account.type);
        }
        operationList.add(builder.build());

        // do not allow empty value insert into database.
        if (!TextUtils.isEmpty(name)) {
            builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
            builder.withValueBackReference(StructuredName.RAW_CONTACT_ID, 0);
            builder.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
            builder.withValue(StructuredName.DISPLAY_NAME, name);
            operationList.add(builder.build());
        }

        if (!TextUtils.isEmpty(phoneNumber)) {
            builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
            builder.withValueBackReference(Phone.RAW_CONTACT_ID, 0);
            builder.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
            builder.withValue(Phone.TYPE, Phone.TYPE_MOBILE);
            builder.withValue(Phone.NUMBER, phoneNumber);
            builder.withValue(Data.IS_PRIMARY, 1);
            operationList.add(builder.build());
        }

        if (anrArray != null) {
            for (String anr : anrArray) {
                if (!TextUtils.isEmpty(anr)) {
                    builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
                    builder.withValueBackReference(Phone.RAW_CONTACT_ID, 0);
                    builder.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
                    builder.withValue(Phone.TYPE, Phone.TYPE_HOME);
                    builder.withValue(Phone.NUMBER, anr);
                    operationList.add(builder.build());
                }
            }
        }

        if (emailAddressArray != null) {
            for (String emailAddress : emailAddressArray) {
                if (!TextUtils.isEmpty(emailAddress)) {
                    builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
                    builder.withValueBackReference(Email.RAW_CONTACT_ID, 0);
                    builder.withValue(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
                    builder.withValue(Email.TYPE, Email.TYPE_MOBILE);
                    builder.withValue(Email.ADDRESS, emailAddress);
                    operationList.add(builder.build());
                }
            }
        }

        try {
            ContentProviderResult[] results =
                    resolver.applyBatch(ContactsContract.AUTHORITY, operationList);
            for (ContentProviderResult result: results) {
                if (result.uri == null) {
                    success = false;
                    break;
                }
            }
            return success;
        } catch (RemoteException e) {
            Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
            return false;
        } catch (OperationApplicationException e) {
            Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
            return false;
        }
    }

    public static Uri insertToCard(Context context, String name, String number, String emails,
            String anrNumber, int subscription) {
        // add the max count limit of Chinese code or not
        if (!TextUtils.isEmpty(name)) {
            final int maxLen = hasChinese(name) ? MAX_LENGTH_NAME_WITH_CHINESE_IN_SIM
                    : MAX_LENGTH_NAME_IN_SIM;
            if (name.length() > maxLen) {
                name = name.substring(0, maxLen);
            }
        }
        Uri result;
        ContentValues mValues = new ContentValues();
        mValues.clear();
        mValues.put(SimContactsConstants.STR_TAG, name);
        if (!TextUtils.isEmpty(number)) {
            number = PhoneNumberUtils.stripSeparators(number);
            if (number.length() > MAX_LENGTH_NUMBER_IN_SIM) {
                number = number.substring(0, MAX_LENGTH_NUMBER_IN_SIM);
            }

            mValues.put(SimContactsConstants.STR_NUMBER, number);
        }
        if (!TextUtils.isEmpty(emails)) {
            mValues.put(SimContactsConstants.STR_EMAILS, emails);
        }
        if (!TextUtils.isEmpty(anrNumber)) {
            anrNumber = anrNumber.replaceAll("[^0123456789PWN\\,\\;\\*\\#\\+\\:]", "");
            mValues.put(SimContactsConstants.STR_ANRS, anrNumber);
        }

        SimContactsOperation mSimContactsOperation = new SimContactsOperation(context);
        result = mSimContactsOperation.insert(mValues, subscription);

        if (result != null) {
            // we should import the contact to the sim account at the same time.
            String[] value = new String[] {
                    name, number, emails, anrNumber
            };
            insertToPhone(value, context.getContentResolver(),subscription);
        } else {
            Log.e(TAG, "export contact: [" + name + ", " + number + ", " + emails + "] to slot "
                    + subscription + " failed");
        }
        return result;
    }

    public static Account getAcount(int sub) {
        Account account = null;
        if (TelephonyManager.getDefault().isMultiSimEnabled()) {
            if (sub == PhoneConstants.SUB1) {
                account = new Account(SimContactsConstants.SIM_NAME_1,
                        SimContactsConstants.ACCOUNT_TYPE_SIM);
            } else if (sub == PhoneConstants.SUB2) {
                account = new Account(SimContactsConstants.SIM_NAME_2,
                        SimContactsConstants.ACCOUNT_TYPE_SIM);
            }
        } else {
            if (sub == PhoneConstants.SUB1) {
                account = new Account(SimContactsConstants.SIM_NAME,
                        SimContactsConstants.ACCOUNT_TYPE_SIM);
            }
        }
        if (account == null) {
            account = new Account(SimContactsConstants.PHONE_NAME,
                    SimContactsConstants.ACCOUNT_TYPE_PHONE);
        }
        return account;
    }

    public static int getEnabledSimCount() {
        int mPhoneCount = TelephonyManager.getDefault().getPhoneCount();
        int enabledSimCount = 0;
        for (int i = 0; i < mPhoneCount; i++) {
            if (TelephonyManager.SIM_STATE_READY == TelephonyManager
                    .getDefault().getSimState(i)) {
                enabledSimCount++;
            }
        }
        return enabledSimCount;
    }

    public static int getSimFreeCount(Context context, int sub) {
        String accountName = getAcount(sub).name;
        int count = 0;

        if (context == null) {
            return 0;
        }

        Cursor queryCursor = context.getContentResolver().query(
                RawContacts.CONTENT_URI,
                new String[] {
                    RawContacts._ID
                },
                RawContacts.ACCOUNT_NAME + " = '" + accountName + "' AND " + RawContacts.DELETED
                        + " = 0", null, null);
        if (queryCursor != null) {
            try {
                count = queryCursor.getCount();
            } finally {
                queryCursor.close();
            }
        }
        return getAdnCount(sub) - count;
    }

    public static int getSpareAnrCount(int sub) {
        int anrCount = 0;
        int[] subId=SubscriptionManager.getSubId(sub);
         try {
                IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(ServiceManager
                        .getService(PHONEBOOK));
                 if (iccIpb != null) {
                   if (subId != null
                        && TelephonyManager.getDefault().isMultiSimEnabled()) {
                    anrCount = iccIpb.getSpareAnrCountUsingSubId(subId[0]);
                } else {
                   anrCount = iccIpb.getSpareAnrCount();
                 }
            }
            } catch (RemoteException ex) {
                // ignore it
            } catch (SecurityException ex) {
                Log.i(TAG, ex.toString());
            } catch (Exception ex) {
        }
        if (DBG) {
            Log.d(TAG, "getSpareAnrCount(" + sub + ") = " + anrCount);
        }
        return anrCount;
    }

    public static int getSpareEmailCount(int sub) {
        int emailCount = 0;
        int[] subId=SubscriptionManager.getSubId(sub);
        try {
                IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(ServiceManager
                        .getService(PHONEBOOK));
                 if (iccIpb != null) {
                if (subId != null
                        && TelephonyManager.getDefault().isMultiSimEnabled()) {
                    emailCount = iccIpb.getSpareEmailCountUsingSubId(subId[0]);
                } else {
                    emailCount = iccIpb.getSpareEmailCount();
                 }
                 }
            } catch (RemoteException ex) {
                // ignore it
            } catch (SecurityException ex) {
                Log.i(TAG, ex.toString());
            } catch (Exception ex) {
        }
        if (DBG) {
            Log.d(TAG, "getSpareEmailCount(" + sub + ") = " + emailCount);
        }
        return emailCount;
    }

    private static boolean hasChinese(String name) {
        return name != null && name.getBytes().length > name.length();
    }

    /**
     * Get SIM card aliases name, which defined in Settings
     */
    public static String getMultiSimAliasesName(Context context, int subscription) {
        if (context == null || subscription < 0) {
            return null;
        }
        String name = "";
        if (TelephonyManager.getDefault().isMultiSimEnabled()) {
            name = Settings.System.getString(context.getContentResolver(),
                    MULTI_SIM_NAME[subscription]);
        }
        if (TextUtils.isEmpty(name)) {
            name = getSimAccountName(subscription);
        }
        return name;
    }

    /**
     * Get SIM card icon index by subscription
     */
    public static int getCurrentSimIconIndex(Context context, int subscription) {
        if (context == null || subscription < PhoneConstants.SUB1
                || subscription >= TelephonyManager.getDefault().getPhoneCount()) {
            return -1;
        }

        String simIconIndex = Settings.System.getString(context.getContentResolver(),
                PREFERRED_SIM_ICON_INDEX);
        if (TextUtils.isEmpty(simIconIndex)) {
            return subscription;
        } else {
            String[] indexs = simIconIndex.split(",");
            if (subscription >= indexs.length) {
                return -1;
            }
            return Integer.parseInt(indexs[subscription]);
        }
    }


    /**
     * Display IP call setting dialog
     */
    public static void showNoIPNumberDialog(final Context mContext, final int subscription) {
        try {
            new AlertDialog.Builder(mContext)
                    .setTitle(R.string.no_ip_number)
                    .setMessage(R.string.no_ip_number_on_sim_card)
                    .setPositiveButton(R.string.set_ip_number,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    setIPNumber(mContext, subscription);
                                }
                            }).setNegativeButton(android.R.string.cancel, null).show();
        } catch (Exception e) {
        }
    }

    /**
     * Setting IP Call number
     */
    public static void setIPNumber(final Context mContext, final int subscription) {
        try {
            LayoutInflater mInflater = LayoutInflater.from(mContext);
            View v = mInflater.inflate(R.layout.ip_prefix_dialog, null);
            final EditText edit = (EditText) v.findViewById(R.id.ip_prefix_dialog_edit);
            String ip_prefix = Settings.System.getString(mContext.getContentResolver(),
                    IPCALL_PREFIX[subscription]);
            edit.setText(ip_prefix);

            new AlertDialog.Builder(mContext).setTitle(R.string.ipcall_dialog_title)
                    .setIcon(android.R.drawable.ic_dialog_info).setView(v)
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String ip_prefix = edit.getText().toString();
                            Settings.System.putString(mContext.getContentResolver(),
                                    IPCALL_PREFIX[subscription], ip_prefix);
                        }
                    }).setNegativeButton(android.R.string.cancel, null).show();
        } catch (Exception e) {
        }
    }

    /**
     * Check one SIM card is enabled
     */
    public static boolean isMultiSimEnable(Context context, int slotId) {
            if (Settings.System.getInt(context.getContentResolver(),
                    Settings.Global.AIRPLANE_MODE_ON, 0) != 0
                || TelephonyManager.SIM_STATE_READY != TelephonyManager
                        .getDefault()
                            .getSimState(slotId)) {
                return false;
            }
            return true;
    }

    /**
     * Get IP Call prefix
     */
    public static String getIPCallPrefix(Context context, int slot) {
        String ipCallPrefix = "";
        if (!TelephonyManager.getDefault().isMultiSimEnabled()) {
            ipCallPrefix = Settings.System.getString(context.getContentResolver(),
                    "ipcall_prefix");
        } else {
            ipCallPrefix = Settings.System.getString(context.getContentResolver(),
                    IPCALL_PREFIX[slot]);
        }
        return ipCallPrefix;
    }

    public static PhoneAccountHandle getAccount(int slot) {
        ComponentName serviceName = new ComponentName("com.android.phone",
                "com.android.services.telephony.TelephonyConnectionService");
        int[] subId = SubscriptionManager.getSubId(slot);
        return new PhoneAccountHandle(serviceName, String.valueOf(subId[0]));
    }
}