summaryrefslogtreecommitdiffstats
path: root/rcs/rcsservice/src/com/android/service/ims/presence/PresencePublication.java
blob: 19a802f83405def1032e524acbc75604dc9abfe7 (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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
/*
 * Copyright (c) 2015, Motorola Mobility LLC
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     - Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     - Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     - Neither the name of Motorola Mobility nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MOTOROLA MOBILITY LLC BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 */

package com.android.service.ims.presence;

import android.annotation.IntDef;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.telecom.PhoneAccount;
import android.telecom.TelecomManager;
import android.telephony.AccessNetworkConstants;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.telephony.ims.RcsContactUceCapability;
import android.telephony.ims.feature.MmTelFeature;
import android.text.TextUtils;

import com.android.ims.ResultCode;
import com.android.ims.internal.ContactNumberUtils;
import com.android.ims.internal.Logger;
import com.android.service.ims.RcsSettingUtils;
import com.android.service.ims.Task;
import com.android.service.ims.TaskManager;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public class PresencePublication extends PresenceBase {
    private Logger logger = Logger.getLogger(this.getClass().getName());

    private final Object mSyncObj = new Object();

    private static final int TIMEOUT_CHECK_SUBSCRIPTION_READY_MS = 5000;

    boolean mMovedToIWLAN = false;
    boolean mMovedToLTE = false;
    boolean mVoPSEnabled = false;

    boolean mIsVolteAvailable = false;
    boolean mIsVtAvailable = false;
    boolean mIsVoWifiAvailable = false;
    boolean mIsViWifiAvailable = false;

    // Queue for the pending PUBLISH request. Just need cache the last one.
    volatile PublishRequest mPendingRequest = null;
    volatile PublishRequest mPublishingRequest = null;
    volatile PublishRequest mPublishedRequest = null;

    /*
     * Message sent to mMsgHandler when there is a new request to Publish capabilities.
     */
    private static final int MESSAGE_RCS_PUBLISH_REQUEST = 1;
    /*
     * Message sent when the default subscription has changed or become active for the first time.
     */
    private static final int MESSAGE_DEFAULT_SUBSCRIPTION_CHANGED = 2;

    private Handler mMsgHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            logger.debug( "Thread=" + Thread.currentThread().getName() + " received "
                    + msg);
            if(msg == null){
                logger.error("msg=null");
                return;
            }

            switch (msg.what) {
                case MESSAGE_RCS_PUBLISH_REQUEST: {
                    logger.debug("handleMessage  msg=RCS_PUBLISH_REQUEST:");

                    PublishRequest publishRequest = (PublishRequest) msg.obj;
                    synchronized (mSyncObj) {
                        mPendingRequest = null;
                    }
                    doPublish(publishRequest);
                    break;
                }
                case MESSAGE_DEFAULT_SUBSCRIPTION_CHANGED: {
                    requestPublishIfSubscriptionReady();
                    break;
                }
                default:
                    logger.debug("handleMessage unknown msg=" + msg.what);
            }
        }
    };

    private PresencePublisher mPresencePublisher;
    private PresenceSubscriber mSubscriber = null;
    static private PresencePublication sPresencePublication = null;

    private boolean mHasCachedTrigger = false;
    private boolean mGotTriggerFromStack = false;
    private boolean mDonotRetryUntilPowerCycle = false;
    private boolean mSimLoaded = false;
    private int mPreferredTtyMode = TelecomManager.TTY_MODE_OFF;

    private boolean mImsRegistered = false;
    private boolean mVtEnabled = false;
    private boolean mDataEnabled = false;
    private final String[] mConfigVolteProvisionErrorOnPublishResponse;
    private final String[] mConfigRcsProvisionErrorOnPublishResponse;
    private int mAssociatedSubscription = SubscriptionManager.INVALID_SUBSCRIPTION_ID;

    /** ETag expired. */
    public static final int UCE_PRES_PUBLISH_TRIGGER_ETAG_EXPIRED = 0;
    /** Move to LTE with VoPS disabled. */
    public static final int UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_LTE_VOPS_DISABLED = 1;
    /** Move to LTE with VoPS enabled. */
    public static final int UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_LTE_VOPS_ENABLED = 2;
    /** Move to eHRPD. */
    public static final int UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_EHRPD = 3;
    /** Move to HSPA+. */
    public static final int UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_HSPAPLUS = 4;
    /** Move to 3G. */
    public static final int UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_3G = 5;
    /** Move to 2G. */
    public static final int UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_2G = 6;
    /** Move to WLAN */
    public static final int UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_WLAN = 7;
    /** Move to IWLAN */
    public static final int UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_IWLAN = 8;
    /** Trigger is unknown. */
    public static final int UCE_PRES_PUBLISH_TRIGGER_UNKNOWN = 9;

    @IntDef(value = {
            UCE_PRES_PUBLISH_TRIGGER_ETAG_EXPIRED,
            UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_LTE_VOPS_DISABLED,
            UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_LTE_VOPS_ENABLED,
            UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_EHRPD,
            UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_HSPAPLUS,
            UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_3G,
            UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_2G,
            UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_WLAN,
            UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_IWLAN,
            UCE_PRES_PUBLISH_TRIGGER_UNKNOWN
    }, prefix="UCE_PRES_PUBLISH_TRIGGER_")
    @Retention(RetentionPolicy.SOURCE)
    public @interface StackPublishTriggerType {}

    public class PublishType {
        public static final int PRES_PUBLISH_TRIGGER_DATA_CHANGED = 0;
        // the lower layer should send trigger when enable volte
        // the lower layer should unpublish when disable volte
        // so only handle VT here.
        public static final int PRES_PUBLISH_TRIGGER_VTCALL_CHANGED = 1;
        public static final int PRES_PUBLISH_TRIGGER_CACHED_TRIGGER = 2;
        public static final int PRES_PUBLISH_TRIGGER_TTY_ENABLE_STATUS = 3;
        public static final int PRES_PUBLISH_TRIGGER_RETRY = 4;
        public static final int PRES_PUBLISH_TRIGGER_FEATURE_AVAILABILITY_CHANGED = 5;
        public static final int PRES_PUBLISH_TRIGGER_DEFAULT_SUB_CHANGED = 6;
    };

    public PresencePublication(PresencePublisher presencePublisher, Context context,
            String[] configVolteProvisionErrorOnPublishResponse,
            String[] configRcsProvisionErrorOnPublishResponse) {
        super(context);
        logger.debug("PresencePublication constrcuct");
        synchronized(mSyncObj) {
            this.mPresencePublisher = presencePublisher;
        }
        mConfigVolteProvisionErrorOnPublishResponse = configVolteProvisionErrorOnPublishResponse;
        mConfigRcsProvisionErrorOnPublishResponse = configRcsProvisionErrorOnPublishResponse;

        mVtEnabled = RcsSettingUtils.isVtEnabledByUser(mAssociatedSubscription);

        mDataEnabled = Settings.Global.getInt(mContext.getContentResolver(),
                    Settings.Global.MOBILE_DATA, 1) == 1;
        logger.debug("The current mobile data is: " + (mDataEnabled ? "enabled" : "disabled"));

        TelecomManager tm = mContext.getSystemService(TelecomManager.class);
        mPreferredTtyMode = tm.getCurrentTtyMode();
        logger.debug("The current TTY mode is: " + mPreferredTtyMode);

        sPresencePublication = this;
    }

    public void updatePresencePublisher(PresencePublisher presencePublisher) {
        synchronized(mSyncObj) {
            logger.debug("Update PresencePublisher");
            this.mPresencePublisher = presencePublisher;
        }
    }

    public void removePresencePublisher() {
        synchronized(mSyncObj) {
            logger.debug("Remove PresencePublisher");
            this.mPresencePublisher = null;
        }
    }

    private void requestPublishIfSubscriptionReady() {
        if (!SubscriptionManager.isValidSubscriptionId(mAssociatedSubscription)) {
            // pulled out the SIM, set it as the same as power on status:
            logger.print("subscription changed to invalid, setting to not published");

            // only reset when the SIM gets absent.
            reset();
            mSimLoaded = false;
            setPublishState(PUBLISH_STATE_NOT_PUBLISHED);
            return;
        }
        if (isSimLoaded()) {
            logger.print("subscription ready, requesting publish");
            mSimLoaded = true;
            // treat hot SIM hot swap as power on.
            mDonotRetryUntilPowerCycle = false;
            requestLocalPublish(PublishType.PRES_PUBLISH_TRIGGER_DEFAULT_SUB_CHANGED);
        } else {
            mMsgHandler.removeMessages(MESSAGE_DEFAULT_SUBSCRIPTION_CHANGED);
            mMsgHandler.sendMessageDelayed(
                    mMsgHandler.obtainMessage(MESSAGE_DEFAULT_SUBSCRIPTION_CHANGED),
                    TIMEOUT_CHECK_SUBSCRIPTION_READY_MS);
        }
    }

    private boolean isSimLoaded() {
        TelephonyManager teleMgr = (TelephonyManager) mContext.getSystemService(
                Context.TELEPHONY_SERVICE);
        if (teleMgr == null) return false;
        teleMgr = teleMgr.createForSubscriptionId(mAssociatedSubscription);
        String[] myImpu = teleMgr.getIsimImpu();
        String myDomain = teleMgr.getIsimDomain();
        String line1Number = teleMgr.getLine1Number();
        return !TextUtils.isEmpty(line1Number) || (!TextUtils.isEmpty(myDomain) && myImpu != null
                && myImpu.length != 0);
    }

    private boolean isIPVoiceSupported(boolean volteAvailable, boolean voWifiAvailable) {
        // volte and vowifi can be enabled separately
        if(!RcsSettingUtils.isVoLteSupported(mAssociatedSubscription) &&
                !RcsSettingUtils.isVoWiFiSupported(mAssociatedSubscription)) {
            logger.print("Disabled by platform, voiceSupported=false");
            return false;
        }

        if(!RcsSettingUtils.isVoLteProvisioned(mAssociatedSubscription) &&
                !RcsSettingUtils.isVowifiProvisioned(mAssociatedSubscription)) {
            logger.print("Wasn't provisioned, voiceSupported=false");
            return false;
        }

        if(!RcsSettingUtils.isAdvancedCallingEnabledByUser(mAssociatedSubscription) &&
                !RcsSettingUtils.isWfcEnabledByUser(mAssociatedSubscription)){
            logger.print("User didn't enable volte or wfc, voiceSupported=false");
            return false;
        }

        // for IWLAN. All WFC settings and provision should be fine if voWifiAvailable is true.
        if(isOnIWLAN()) {
            boolean voiceSupported=volteAvailable || voWifiAvailable;
            logger.print("on IWLAN, voiceSupported=" + voiceSupported);
            return voiceSupported;
        }

        // for none-IWLAN
        if(!isOnLTE()) {
            logger.print("isOnLTE=false, voiceSupported=false");
            return false;
        }

        if(!mVoPSEnabled) {
            logger.print("mVoPSEnabled=false, voiceSupported=false");
            return false;
        }

        logger.print("voiceSupported=true");
        return true;
    }

    private boolean isIPVideoSupported(boolean vtAvailable, boolean viWifiAvailable) {
        // if volte or vt was disabled then the viwifi will be disabled as well.
        if(!RcsSettingUtils.isVoLteSupported(mAssociatedSubscription) ||
                !RcsSettingUtils.isVtSupported(mAssociatedSubscription)) {
            logger.print("Disabled by platform, videoSupported=false");
            return false;
        }

        if(!RcsSettingUtils.isVoLteProvisioned(mAssociatedSubscription) ||
                !RcsSettingUtils.isLvcProvisioned(mAssociatedSubscription)) {
            logger.print("Not provisioned. videoSupported=false");
            return false;
        }

        if(!RcsSettingUtils.isAdvancedCallingEnabledByUser(mAssociatedSubscription) || !mVtEnabled){
            logger.print("User disabled volte or vt, videoSupported=false");
            return false;
        }

        if(isTtyOn()){
            logger.print("isTtyOn=true, videoSupported=false");
            return false;
        }

        // for IWLAN, all WFC settings and provision should be fine if viWifiAvailable is true.
        if(isOnIWLAN()) {
            boolean videoSupported = vtAvailable || viWifiAvailable;
            logger.print("on IWLAN, videoSupported=" + videoSupported);
            return videoSupported;
        }

        if(!isDataEnabled()) {
            logger.print("isDataEnabled()=false, videoSupported=false");
            return false;
        }

        if(!isOnLTE()) {
            logger.print("isOnLTE=false, videoSupported=false");
            return false;
        }

        if(!mVoPSEnabled) {
            logger.print("mVoPSEnabled=false, videoSupported=false");
            return false;
        }

        return true;
    }

    public void onTtyPreferredModeChanged(int newTtyPreferredMode) {
        logger.debug("Tty mode changed from " + mPreferredTtyMode
                + " to " + newTtyPreferredMode);

        boolean mIsTtyEnabled = isTtyEnabled(mPreferredTtyMode);
        boolean isTtyEnabled = isTtyEnabled(newTtyPreferredMode);
        mPreferredTtyMode = newTtyPreferredMode;
        if (mIsTtyEnabled != isTtyEnabled) {
            logger.print("ttyEnabled status changed from " + mIsTtyEnabled
                    + " to " + isTtyEnabled);
            requestLocalPublish(PresencePublication.PublishType.
                    PRES_PUBLISH_TRIGGER_TTY_ENABLE_STATUS );
        }
    }

    public void onAirplaneModeChanged(boolean isAirplaneModeEnabled) {
        if(isAirplaneModeEnabled){
            logger.print("Airplane mode, set to PUBLISH_STATE_NOT_PUBLISHED");
            reset();
            setPublishState(PUBLISH_STATE_NOT_PUBLISHED);
        }
    }

    public boolean isTtyOn() {
        logger.debug("isTtyOn settingsTtyMode=" + mPreferredTtyMode);
        return isTtyEnabled(mPreferredTtyMode);
    }

    public void onImsConnected() {
        mImsRegistered = true;
    }

    public void onImsDisconnected() {
        logger.debug("reset PUBLISH status for IMS had been disconnected");
        mImsRegistered = false;
        reset();
    }

    private void reset() {
        mIsVolteAvailable = false;
        mIsVtAvailable = false;
        mIsVoWifiAvailable = false;
        mIsViWifiAvailable = false;

        synchronized(mSyncObj) {
            mPendingRequest = null; //ignore the previous request
            mPublishingRequest = null;
            mPublishedRequest = null;
        }
    }

    public void handleAssociatedSubscriptionChanged(int newSubId) {
        if (mAssociatedSubscription == newSubId) {
            return;
        }
        reset();
        mAssociatedSubscription = newSubId;
        mMsgHandler.removeMessages(MESSAGE_DEFAULT_SUBSCRIPTION_CHANGED);
        mMsgHandler.sendMessage(mMsgHandler.obtainMessage(MESSAGE_DEFAULT_SUBSCRIPTION_CHANGED));
    }

    public void handleProvisioningChanged() {
        if(RcsSettingUtils.isEabProvisioned(mContext, mAssociatedSubscription)) {
            logger.debug("provisioned, set mDonotRetryUntilPowerCycle to false");
            mDonotRetryUntilPowerCycle = false;
            if(mHasCachedTrigger) {
                requestLocalPublish(PublishType.PRES_PUBLISH_TRIGGER_CACHED_TRIGGER);
            }
        }
    }

    static public PresencePublication getPresencePublication() {
        return sPresencePublication;
    }

    public void setSubscriber(PresenceSubscriber subscriber) {
        mSubscriber = subscriber;
    }

    public boolean isDataEnabled() {
        return  Settings.Global.getInt(mContext.getContentResolver(),
                Settings.Global.MOBILE_DATA, 1) == 1;
    }

    public void onMobileDataChanged(boolean value){
        logger.print("onMobileDataChanged, mDataEnabled=" + mDataEnabled + " value=" + value);
        if(mDataEnabled != value) {
            mDataEnabled = value;

            requestLocalPublish(PublishType.PRES_PUBLISH_TRIGGER_DATA_CHANGED);
        }
    }

    public void onVtEnabled(boolean enabled) {
        logger.debug("onVtEnabled mVtEnabled=" + mVtEnabled + " enabled=" + enabled);

        if(mVtEnabled != enabled) {
            mVtEnabled = enabled;
            requestLocalPublish(PublishType.PRES_PUBLISH_TRIGGER_VTCALL_CHANGED);
        }
    }

    @Override
    public void onCommandStatusUpdated(int taskId, int requestId, int resultCode) {
        logger.info("onCommandStatusUpdated: resultCode= " + resultCode);
        super.onCommandStatusUpdated(taskId, requestId, resultCode);
    }

    /**
     * @return return true if it had been PUBLISHED.
     */
    private boolean isPublishedOrPublishing() {
        long publishThreshold = RcsSettingUtils.getPublishThrottle(mAssociatedSubscription);

        boolean publishing = false;
        publishing = (mPublishingRequest != null) &&
                (System.currentTimeMillis() - mPublishingRequest.getTimestamp()
                <= publishThreshold);

        return (getPublishState() == PUBLISH_STATE_200_OK || publishing);
    }

    /**
     * @return The result of the last Publish request.
     */
    public @PresenceBase.PresencePublishState int getPublishState() {
        PresencePublisher presencePublisher = null;
        synchronized(mSyncObj) {
            presencePublisher = mPresencePublisher;
        }

        if (presencePublisher != null) {
            return presencePublisher.getPublisherState();
        }
        return PUBLISH_STATE_NOT_PUBLISHED;
    }

    /**
     * @param publishState The result of the last publish request.
     */
    public void setPublishState(int publishState) {
        PresencePublisher presencePublisher = null;
        synchronized(mSyncObj) {
            presencePublisher = mPresencePublisher;
        }

        if (presencePublisher != null) {
            presencePublisher.updatePublisherState(publishState);
        }
    }

    // Trigger a local publish based off of state changes in the framework.
    private void requestLocalPublish(int trigger) {

        // if the value is true then it will call stack to send the PUBLISH
        // though the previous publish had the same capability
        // for example: for retry PUBLISH.
        boolean bForceToNetwork = true;
        switch(trigger)
        {
            case PublishType.PRES_PUBLISH_TRIGGER_DATA_CHANGED:
            {
                logger.print("PRES_PUBLISH_TRIGGER_DATA_CHANGED");
                bForceToNetwork = false;
                break;
            }
            case PublishType.PRES_PUBLISH_TRIGGER_VTCALL_CHANGED:
            {
                logger.print("PRES_PUBLISH_TRIGGER_VTCALL_CHANGED");
                // Didn't get featureCapabilityChanged sometimes.
                bForceToNetwork = true;
                break;
            }
            case PublishType.PRES_PUBLISH_TRIGGER_CACHED_TRIGGER:
            {
                logger.print("PRES_PUBLISH_TRIGGER_CACHED_TRIGGER");
                break;
            }
            case PublishType.PRES_PUBLISH_TRIGGER_TTY_ENABLE_STATUS:
            {
                logger.print("PRES_PUBLISH_TRIGGER_TTY_ENABLE_STATUS");
                bForceToNetwork = true;

                break;
            }
            case PublishType.PRES_PUBLISH_TRIGGER_FEATURE_AVAILABILITY_CHANGED:
            {
                bForceToNetwork = false;
                logger.print("PRES_PUBLISH_TRIGGER_FEATURE_AVAILABILITY_CHANGED");
                break;
            }
            case PublishType.PRES_PUBLISH_TRIGGER_RETRY:
            {
                logger.print("PRES_PUBLISH_TRIGGER_RETRY");
                break;
            }
            case PublishType.PRES_PUBLISH_TRIGGER_DEFAULT_SUB_CHANGED:
            {
                logger.print("PRES_PUBLISH_TRIGGER_DEFAULT_SUB_CHANGED");
                bForceToNetwork = true;
                break;
            }
            default:
            {
                logger.print("Unknown publish trigger from AP");
            }
        }

        if(mGotTriggerFromStack == false){
            // Waiting for RCS stack get ready.
            logger.print("Didn't get trigger from stack yet, discard framework trigger.");
            return;
        }

        if (mDonotRetryUntilPowerCycle) {
            logger.print("Don't publish until next power cycle");
            return;
        }

        if(!mSimLoaded){
            //need to read some information from SIM to publish
            logger.print("invokePublish cache the trigger since the SIM is not ready");
            mHasCachedTrigger = true;
            return;
        }

        //the provision status didn't be read from modem yet
        if(!RcsSettingUtils.isEabProvisioned(mContext, mAssociatedSubscription)) {
            logger.print("invokePublish cache the trigger, not provision yet");
            mHasCachedTrigger = true;
            return;
        }

        PublishRequest publishRequest = new PublishRequest(
                bForceToNetwork, System.currentTimeMillis());

        requestPublication(publishRequest);

        return;
    }

    public void onStackPublishRequested(@StackPublishTriggerType int publishTriggerType) {
        mGotTriggerFromStack = true;

        switch (publishTriggerType)
        {
            case UCE_PRES_PUBLISH_TRIGGER_ETAG_EXPIRED:
            {
                logger.print("PUBLISH_TRIGGER_ETAG_EXPIRED");
                break;
            }
            case UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_LTE_VOPS_DISABLED:
            {
                logger.print("PUBLISH_TRIGGER_MOVE_TO_LTE_VOPS_DISABLED");
                mMovedToLTE = true;
                mVoPSEnabled = false;
                mMovedToIWLAN = false;

                // onImsConnected could came later than this trigger.
                mImsRegistered = true;
                break;
            }
            case UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_LTE_VOPS_ENABLED:
            {
                logger.print("PUBLISH_TRIGGER_MOVE_TO_LTE_VOPS_ENABLED");
                mMovedToLTE = true;
                mVoPSEnabled = true;
                mMovedToIWLAN = false;

                // onImsConnected could came later than this trigger.
                mImsRegistered = true;
                break;
            }
            case UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_IWLAN:
            {
                logger.print("QRCS_PRES_PUBLISH_TRIGGER_MOVE_TO_IWLAN");
                mMovedToLTE = false;
                mVoPSEnabled = false;
                mMovedToIWLAN = true;

                // onImsConnected could came later than this trigger.
                mImsRegistered = true;
                break;
            }
            case UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_EHRPD:
            {
                logger.print("PUBLISH_TRIGGER_MOVE_TO_EHRPD");
                mMovedToLTE = false;
                mVoPSEnabled = false;
                mMovedToIWLAN = false;

                // onImsConnected could came later than this trigger.
                mImsRegistered = true;
                break;
            }
            case UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_HSPAPLUS:
            {
                logger.print("PUBLISH_TRIGGER_MOVE_TO_HSPAPLUS");
                mMovedToLTE = false;
                mVoPSEnabled = false;
                mMovedToIWLAN = false;
                break;
            }
            case UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_2G:
            {
                logger.print("PUBLISH_TRIGGER_MOVE_TO_2G");
                mMovedToLTE = false;
                mVoPSEnabled = false;
                mMovedToIWLAN = false;
                break;
            }
            case UCE_PRES_PUBLISH_TRIGGER_MOVE_TO_3G:
            {
                logger.print("PUBLISH_TRIGGER_MOVE_TO_3G");
                mMovedToLTE = false;
                mVoPSEnabled = false;
                mMovedToIWLAN = false;
                break;
            }
            default:
                logger.print("Unknow Publish Trigger Type");
        }

        if (mDonotRetryUntilPowerCycle) {
            logger.print("Don't publish until next power cycle");
            return;
        }

        if(!mSimLoaded){
            //need to read some information from SIM to publish
            logger.print("invokePublish cache the trigger since the SIM is not ready");
            mHasCachedTrigger = true;
            return;
        }

        //the provision status didn't be read from modem yet
        if(!RcsSettingUtils.isEabProvisioned(mContext, mAssociatedSubscription)) {
            logger.print("invokePublish cache the trigger, not provision yet");
            mHasCachedTrigger = true;
            return;
        }

        // Always send the PUBLISH when we got the trigger from stack.
        // This can avoid any issue when switch the phone between IWLAN and LTE.
        PublishRequest publishRequest = new PublishRequest(
                true /*forceToNetwork*/, System.currentTimeMillis());

        requestPublication(publishRequest);
    }

    /**
     * Trigger a publish when the stack becomes available and we have a cached trigger waiting.
     */
    public void onStackAvailable() {
        if (mHasCachedTrigger) {
            requestLocalPublish(PublishType.PRES_PUBLISH_TRIGGER_CACHED_TRIGGER);
        }
    }

    public class PublishRequest {
        private boolean mForceToNetwork;
        private long mCurrentTime;
        private boolean mVolteCapable = false;
        private boolean mVtCapable = false;

        PublishRequest(boolean bForceToNetwork, long currentTime) {
            refreshPublishContent();
            mForceToNetwork = bForceToNetwork;
            mCurrentTime = currentTime;
        }

        public void refreshPublishContent() {
            setVolteCapable(isIPVoiceSupported(mIsVolteAvailable, mIsVoWifiAvailable));
            setVtCapable(isIPVideoSupported(mIsVtAvailable, mIsViWifiAvailable));
        }

        public boolean getForceToNetwork() {
            return mForceToNetwork;
        }

        public void setForceToNetwork(boolean bForceToNetwork) {
            mForceToNetwork = bForceToNetwork;
        }

        public long getTimestamp() {
            return mCurrentTime;
        }

        public void setTimestamp(long currentTime) {
            mCurrentTime = currentTime;
        }

        public void setVolteCapable(boolean capable) {
            mVolteCapable = capable;
        }

        public void setVtCapable(boolean capable) {
            mVtCapable = capable;
        }

        public boolean getVolteCapable() {
            return mVolteCapable;
        }

        public boolean getVtCapable() {
            return mVtCapable;
        }

        public boolean hasSamePublishContent(PublishRequest request) {
            if(request == null) {
                logger.error("request == null");
                return false;
            }

            return (mVolteCapable == request.getVolteCapable() &&
                    mVtCapable == request.getVtCapable());
        }

        public String toString(){
            return "mForceToNetwork=" + mForceToNetwork +
                    " mCurrentTime=" + mCurrentTime +
                    " mVolteCapable=" + mVolteCapable +
                    " mVtCapable=" + mVtCapable;
        }
    }

    private void requestPublication(PublishRequest publishRequest) {
        // this is used to avoid the temp false feature change when switched between network.
        if(publishRequest == null) {
            logger.error("Invalid parameter publishRequest == null");
            return;
        }

        long requestThrottle = 2000;
        long currentTime = System.currentTimeMillis();
        synchronized(mSyncObj){
            // There is a PUBLISH will be done soon. Discard it
            if((mPendingRequest != null) && currentTime - mPendingRequest.getTimestamp()
                    <= requestThrottle) {
                logger.print("A publish is pending, update the pending request and discard this one");
                if(publishRequest.getForceToNetwork() && !mPendingRequest.getForceToNetwork()) {
                    mPendingRequest.setForceToNetwork(true);
                }
                mPendingRequest.setTimestamp(publishRequest.getTimestamp());
                return;
            }

            mPendingRequest = publishRequest;
        }

        Message publishMessage = mMsgHandler.obtainMessage(
                MESSAGE_RCS_PUBLISH_REQUEST, mPendingRequest);
        mMsgHandler.sendMessageDelayed(publishMessage, requestThrottle);
    }

    private void doPublish(PublishRequest publishRequest) {

        if(publishRequest == null) {
            logger.error("publishRequest == null");
            return;
        }

        PresencePublisher presencePublisher = null;
        synchronized(mSyncObj) {
            presencePublisher = mPresencePublisher;
        }

        if (presencePublisher == null) {
            logger.error("mPresencePublisher == null");
            return;
        }

        if(!mImsRegistered) {
            logger.error("IMS wasn't registered");
            return;
        }

        // Since we are doing a publish, don't need the retry any more.
        if(mPendingRetry) {
            mPendingRetry = false;
            mAlarmManager.cancel(mRetryAlarmIntent);
        }

        // always publish the latest status.
        synchronized(mSyncObj) {
            publishRequest.refreshPublishContent();
        }

        logger.print("publishRequest=" + publishRequest);
        if(!publishRequest.getForceToNetwork() && isPublishedOrPublishing() &&
                (publishRequest.hasSamePublishContent(mPublishingRequest) ||
                        (mPublishingRequest == null) &&
                        publishRequest.hasSamePublishContent(mPublishedRequest)) &&
                (getPublishState() != PUBLISH_STATE_NOT_PUBLISHED)) {
            logger.print("Don't need publish since the capability didn't change publishRequest "
                    + publishRequest + " getPublishState()=" + getPublishState());
            return;
        }

        // Don't publish too frequently. Checking the throttle timer.
        if(isPublishedOrPublishing()) {
            if(mPendingRetry) {
                logger.print("Pending a retry");
                return;
            }

            long publishThreshold = RcsSettingUtils.getPublishThrottle(mAssociatedSubscription);
            long passed = publishThreshold;
            if(mPublishingRequest != null) {
                passed = System.currentTimeMillis() - mPublishingRequest.getTimestamp();
            } else if(mPublishedRequest != null) {
                passed = System.currentTimeMillis() - mPublishedRequest.getTimestamp();
            }
            passed = passed>=0?passed:publishThreshold;

            long left = publishThreshold - passed;
            left = left>120000?120000:left; // Don't throttle more then 2 mintues.
            if(left > 0) {
                // A publish is ongoing or published in 1 minute.
                // Since the new publish has new status. So schedule
                // the publish after the throttle timer.
                scheduleRetryPublish(left);
                return;
            }
        }

        // we need send PUBLISH once even the volte is off when power on the phone.
        // That will tell other phone that it has no volte/vt capability.
        if(!RcsSettingUtils.isAdvancedCallingEnabledByUser(mAssociatedSubscription) &&
                getPublishState() != PUBLISH_STATE_NOT_PUBLISHED) {
            // volte was not enabled.
            // or it is turnning off volte. lower layer should unpublish
            reset();
            return;
        }

        TelephonyManager teleMgr = (TelephonyManager) mContext.getSystemService(
                Context.TELEPHONY_SERVICE);
        teleMgr = teleMgr.createForSubscriptionId(mAssociatedSubscription);
        if (teleMgr == null) {
            logger.error("TelephonyManager not available.");
            return;
        }
        Uri contactUri = Uri.fromParts(PhoneAccount.SCHEME_TEL, teleMgr.getLine1Number(), null);

        RcsContactUceCapability.Builder presenceInfoBuilder =
                new RcsContactUceCapability.Builder(contactUri);
        if (publishRequest.getVolteCapable()) {
            presenceInfoBuilder.add(RcsContactUceCapability.CAPABILITY_IP_VOICE_CALL);
        }
        if (publishRequest.getVtCapable()) {
            presenceInfoBuilder.add(RcsContactUceCapability.CAPABILITY_IP_VIDEO_CALL);
        }

        synchronized(mSyncObj) {
            mPublishingRequest = publishRequest;
            mPublishingRequest.setTimestamp(System.currentTimeMillis());
        }

        String myUri = getUriForPublication();
        if (myUri == null) {
            logger.error("doPublish, myUri is null");
        }
        String myNumber = getNumberFromUri(myUri);
        int taskId = TaskManager.getDefault().addPublishTask(myNumber);
        logger.print("doPublish, uri=" + myUri + ", myNumber=" + myNumber + ", taskId=" + taskId);

        int ret = presencePublisher.requestPublication(presenceInfoBuilder.build(), myUri, taskId);
        if (ret != ResultCode.SUCCESS) {
            logger.print("doPublish, task=" + taskId + " failed with code=" + ret);
            TaskManager.getDefault().removeTask(taskId);
        }
        // cache the latest publication request if temporarily not available.
        mHasCachedTrigger = (ret == ResultCode.ERROR_SERVICE_NOT_AVAILABLE);
    }

    private String getNumberFromUri(String uriString) {
        String number = Uri.parse(uriString).getSchemeSpecificPart();
        String[] numberParts = number.split("[@;:]");

        if (numberParts.length == 0) {
            logger.error("getNumberFromUri: invalid uri=" + uriString);
            return null;
        }
        return numberParts[0];
    }

    private String getUriForPublication() {
        TelephonyManager teleMgr = (TelephonyManager) mContext.getSystemService(
                Context.TELEPHONY_SERVICE);
        if (teleMgr == null) {
            logger.error("getUriForPublication, teleMgr = null");
            return null;
        }
        teleMgr = teleMgr.createForSubscriptionId(mAssociatedSubscription);

        String myNumUri = null;
        String myDomain = teleMgr.getIsimDomain();
        logger.debug("myDomain=" + myDomain);
        if (myDomain != null && !TextUtils.isEmpty(myDomain)) {
            String[] impu = teleMgr.getIsimImpu();

            if(impu !=null){
                for(int i=0; i<impu.length; i++){
                    logger.debug("impu[" + i + "]=" + impu[i]);
                    if(impu[i] != null && impu[i].startsWith("sip:") &&
                            impu[i].endsWith(myDomain)){
                        myNumUri = impu[i];
                        break;
                    }
                }
            }
        }
        String myNumber = null;
        if (myNumUri != null) {
            myNumber = Uri.parse(myNumUri).getSchemeSpecificPart();
        }

        if (myNumber == null) {
            myNumber = ContactNumberUtils.getDefault().format(teleMgr.getLine1Number());
            if (myDomain != null && !TextUtils.isEmpty(myDomain)) {
                myNumUri = "sip:" + myNumber + "@" + myDomain;
            } else {
                myNumUri = "tel:" + myNumber;
            }
        }
        return myNumUri;
    }

    private PendingIntent mRetryAlarmIntent = null;
    public static final String ACTION_RETRY_PUBLISH_ALARM =
            "com.android.service.ims.presence.retry.publish";
    private AlarmManager mAlarmManager = null;
    boolean mCancelRetry = true;
    boolean mPendingRetry = false;

    private void scheduleRetryPublish(long timeSpan) {
        logger.print("timeSpan=" + timeSpan +
                " mPendingRetry=" + mPendingRetry +
                " mCancelRetry=" + mCancelRetry);

        // avoid duplicated retry.
        if(mPendingRetry) {
            logger.debug("There was a retry already");
            return;
        }
        mPendingRetry = true;
        mCancelRetry = false;

        Intent intent = new Intent(ACTION_RETRY_PUBLISH_ALARM);
        intent.setPackage(mContext.getPackageName());
        mRetryAlarmIntent = PendingIntent.getBroadcast(mContext, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        if(mAlarmManager == null) {
            mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        }

        mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + timeSpan, mRetryAlarmIntent);
    }

    public void retryPublish() {
        logger.print("mCancelRetry=" + mCancelRetry);
        mPendingRetry = false;

        // Need some time to cancel it (1 minute for longest)
        // Don't do it if it was canceled already.
        if(mCancelRetry) {
            return;
        }

        requestLocalPublish(PublishType.PRES_PUBLISH_TRIGGER_RETRY);
    }

    public void onSipResponse(int requestId, int responseCode, String reasonPhrase) {
        logger.print( "Publish response code = " + responseCode
                +"Publish response reason phrase = " + reasonPhrase);

        synchronized(mSyncObj) {
            mPublishedRequest = mPublishingRequest;
            mPublishingRequest = null;
        }

        if (isInConfigList(responseCode, reasonPhrase,
                mConfigVolteProvisionErrorOnPublishResponse)) {
            logger.print("volte provision error. sipCode=" + responseCode + " phrase=" +
                    reasonPhrase);
            setPublishState(PUBLISH_STATE_VOLTE_PROVISION_ERROR);
            mDonotRetryUntilPowerCycle = true;

            notifyDm();

            return;
        }

        if (isInConfigList(responseCode, reasonPhrase, mConfigRcsProvisionErrorOnPublishResponse)) {
            logger.print("rcs provision error.sipCode=" + responseCode + " phrase=" + reasonPhrase);
            setPublishState(PUBLISH_STATE_RCS_PROVISION_ERROR);
            mDonotRetryUntilPowerCycle = true;

            return;
        }

        switch (responseCode) {
            case 999:
                logger.debug("Publish ignored - No capability change");
                break;
            case 200:
                setPublishState(PUBLISH_STATE_200_OK);
                if(mSubscriber != null) {
                    mSubscriber.retryToGetAvailability();
                }
                break;

            case 408:
                setPublishState(PUBLISH_STATE_REQUEST_TIMEOUT);
                break;

            default: // Generic Failure
                if ((responseCode < 100) || (responseCode > 699)) {
                    logger.debug("Ignore internal response code, sipCode=" + responseCode);
                    // internal error
                    //  0- PERMANENT ERROR: UI should not retry immediately
                    //  888- TEMP ERROR:  UI Can retry immediately
                    //  999- NO CHANGE: No Publish needs to be sent
                    if(responseCode == 888) {
                        // retry per 2 minutes
                        scheduleRetryPublish(120000);
                    } else {
                        logger.debug("Ignore internal response code, sipCode=" + responseCode);
                    }
                } else {
                    logger.debug( "Generic Failure");
                    setPublishState(PUBLISH_STATE_OTHER_ERROR);

                    if ((responseCode>=400) && (responseCode <= 699)) {
                        // 4xx/5xx/6xx, No retry, no impact on subsequent publish
                        logger.debug( "No Retry in OEM");
                    }
                }
                break;
        }

        // Suppose the request ID had been set when IQPresListener_CMDStatus
        Task task = TaskManager.getDefault().getTaskByRequestId(requestId);
        if(task != null){
            task.mSipResponseCode = responseCode;
            task.mSipReasonPhrase = reasonPhrase;
        }

        handleCallback(task, getPublishState(), false);
    }

    private static boolean isTtyEnabled(int mode) {
        return TelecomManager.TTY_MODE_OFF != mode;
    }

    public void onFeatureCapabilityChanged(int networkType,
            MmTelFeature.MmTelCapabilities capabilities) {
        logger.debug("onFeatureCapabilityChanged networkType=" + networkType
                +", capabilities=" + capabilities);

        Thread thread = new Thread(() -> onFeatureCapabilityChangedInternal(networkType,
                capabilities), "onFeatureCapabilityChangedInternal thread");

        thread.start();
    }

    synchronized private void onFeatureCapabilityChangedInternal(int networkType,
            MmTelFeature.MmTelCapabilities capabilities) {
        boolean oldIsVolteAvailable = mIsVolteAvailable;
        boolean oldIsVtAvailable = mIsVtAvailable;
        boolean oldIsVoWifiAvailable = mIsVoWifiAvailable;
        boolean oldIsViWifiAvailable = mIsViWifiAvailable;

        mIsVolteAvailable = (networkType == AccessNetworkConstants.TRANSPORT_TYPE_WWAN) &&
                capabilities.isCapable(MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE);

        mIsVoWifiAvailable = (networkType == AccessNetworkConstants.TRANSPORT_TYPE_WLAN) &&
                capabilities.isCapable(MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE);

        mIsVtAvailable = (networkType == AccessNetworkConstants.TRANSPORT_TYPE_WWAN) &&
                capabilities.isCapable(MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VIDEO);

        mIsViWifiAvailable = (networkType == AccessNetworkConstants.TRANSPORT_TYPE_WLAN) &&
                capabilities.isCapable(MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VIDEO);

        logger.print("mIsVolteAvailable=" + mIsVolteAvailable +
                " mIsVoWifiAvailable=" + mIsVoWifiAvailable +
                " mIsVtAvailable=" + mIsVtAvailable +
                " mIsViWifiAvailable=" + mIsViWifiAvailable +
                " oldIsVolteAvailable=" + oldIsVolteAvailable +
                " oldIsVoWifiAvailable=" + oldIsVoWifiAvailable +
                " oldIsVtAvailable=" + oldIsVtAvailable +
                " oldIsViWifiAvailable=" + oldIsViWifiAvailable);

        if(oldIsVolteAvailable != mIsVolteAvailable ||
                oldIsVtAvailable != mIsVtAvailable ||
                oldIsVoWifiAvailable != mIsVoWifiAvailable ||
                oldIsViWifiAvailable != mIsViWifiAvailable) {
            if(mGotTriggerFromStack) {
                if((Settings.Global.getInt(mContext.getContentResolver(),
                        Settings.Global.AIRPLANE_MODE_ON, 0) != 0) && !mIsVoWifiAvailable &&
                        !mIsViWifiAvailable) {
                    logger.print("Airplane mode was on and no vowifi and viwifi." +
                        " Don't need publish. Stack will unpublish");
                    return;
                }

                if(isOnIWLAN()) {
                    // will check duplicated PUBLISH in requestPublication by invokePublish
                    requestLocalPublish(PublishType.
                            PRES_PUBLISH_TRIGGER_FEATURE_AVAILABILITY_CHANGED);
                }
            } else {
                mHasCachedTrigger = true;
            }
        }
    }

    private boolean isOnLTE() {
        TelephonyManager teleMgr = (TelephonyManager) mContext.getSystemService(
                Context.TELEPHONY_SERVICE);
            int networkType = teleMgr.getDataNetworkType();
            logger.debug("mMovedToLTE=" + mMovedToLTE + " networkType=" + networkType);

            // Had reported LTE by trigger and still have DATA.
            return mMovedToLTE && (networkType != TelephonyManager.NETWORK_TYPE_UNKNOWN);
    }

    private boolean isOnIWLAN() {
        TelephonyManager teleMgr = (TelephonyManager) mContext.getSystemService(
                Context.TELEPHONY_SERVICE);
            int networkType = teleMgr.getDataNetworkType();
            logger.debug("mMovedToIWLAN=" + mMovedToIWLAN + " networkType=" + networkType);

            // Had reported IWLAN by trigger and still have DATA.
            return mMovedToIWLAN && (networkType != TelephonyManager.NETWORK_TYPE_UNKNOWN);
    }
}