summaryrefslogtreecommitdiff
path: root/src/com/android/server/telecom/TelecomSystem.java
blob: da325f71b5e041ab08fe8090bbe11a0bfc27d876 (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
/*
 * Copyright (C) 2014 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.server.telecom;

import android.Manifest;
import android.app.ActivityManager;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.BugreportManager;
import android.os.DropBoxManager;
import android.os.UserHandle;
import android.os.UserManager;
import android.telecom.Log;
import android.telecom.PhoneAccountHandle;
import android.telephony.AnomalyReporter;
import android.telephony.TelephonyManager;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.android.internal.annotations.VisibleForTesting;
import com.android.server.telecom.CallAudioManager.AudioServiceFactory;
import com.android.server.telecom.DefaultDialerCache.DefaultDialerManagerAdapter;
import com.android.server.telecom.bluetooth.BluetoothDeviceManager;
import com.android.server.telecom.bluetooth.BluetoothRouteManager;
import com.android.server.telecom.bluetooth.BluetoothStateReceiver;
import com.android.server.telecom.callfiltering.BlockedNumbersAdapter;
import com.android.server.telecom.components.UserCallIntentProcessor;
import com.android.server.telecom.components.UserCallIntentProcessorFactory;
import com.android.server.telecom.ui.AudioProcessingNotification;
import com.android.server.telecom.ui.CallStreamingNotification;
import com.android.server.telecom.ui.DisconnectedCallNotifier;
import com.android.server.telecom.ui.IncomingCallNotifier;
import com.android.server.telecom.ui.MissedCallNotifierImpl.MissedCallNotifierImplFactory;
import com.android.server.telecom.ui.ToastFactory;
import com.android.server.telecom.voip.TransactionManager;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Top-level Application class for Telecom.
 */
public class TelecomSystem {

    /**
     * This interface is implemented by system-instantiated components (e.g., Services and
     * Activity-s) that wish to use the TelecomSystem but would like to be testable. Such a
     * component should implement the getTelecomSystem() method to return the global singleton,
     * and use its own method. Tests can subclass the component to return a non-singleton.
     *
     * A refactoring goal for Telecom is to limit use of the TelecomSystem singleton to those
     * system-instantiated components, and have all other parts of the system just take all their
     * dependencies as explicit arguments to their constructor or other methods.
     */
    public interface Component {
        TelecomSystem getTelecomSystem();
    }


    /**
     * Tagging interface for the object used for synchronizing multi-threaded operations in
     * the Telecom system.
     */
    public interface SyncRoot {
    }

    private static final IntentFilter USER_SWITCHED_FILTER =
            new IntentFilter(Intent.ACTION_USER_SWITCHED);

    private static final IntentFilter USER_STARTING_FILTER =
            new IntentFilter(Intent.ACTION_USER_STARTING);

    private static final IntentFilter BOOT_COMPLETE_FILTER =
            new IntentFilter(Intent.ACTION_BOOT_COMPLETED);

    /** Intent filter for dialer secret codes. */
    private static final IntentFilter DIALER_SECRET_CODE_FILTER;

    /**
     * Initializes the dialer secret code intent filter.  Setup to handle the various secret codes
     * which can be dialed (e.g. in format *#*#code#*#*) to trigger various behavior in Telecom.
     */
    static {
        DIALER_SECRET_CODE_FILTER = new IntentFilter(
                "android.provider.Telephony.SECRET_CODE");
        DIALER_SECRET_CODE_FILTER.addDataScheme("android_secret_code");
        DIALER_SECRET_CODE_FILTER
                .addDataAuthority(DialerCodeReceiver.TELECOM_SECRET_CODE_DEBUG_ON, null);
        DIALER_SECRET_CODE_FILTER
                .addDataAuthority(DialerCodeReceiver.TELECOM_SECRET_CODE_DEBUG_OFF, null);
        DIALER_SECRET_CODE_FILTER
                .addDataAuthority(DialerCodeReceiver.TELECOM_SECRET_CODE_MARK, null);
        DIALER_SECRET_CODE_FILTER
                .addDataAuthority(DialerCodeReceiver.TELECOM_SECRET_CODE_MENU, null);

        USER_SWITCHED_FILTER.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        USER_STARTING_FILTER.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        BOOT_COMPLETE_FILTER.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        DIALER_SECRET_CODE_FILTER.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
    }

    private static TelecomSystem INSTANCE = null;

    private final SyncRoot mLock = new SyncRoot() { };
    private final MissedCallNotifier mMissedCallNotifier;
    private final IncomingCallNotifier mIncomingCallNotifier;
    private final PhoneAccountRegistrar mPhoneAccountRegistrar;
    private final CallsManager mCallsManager;
    private final RespondViaSmsManager mRespondViaSmsManager;
    private final Context mContext;
    private final CallIntentProcessor mCallIntentProcessor;
    private final TelecomBroadcastIntentProcessor mTelecomBroadcastIntentProcessor;
    private final TelecomServiceImpl mTelecomServiceImpl;
    private final ContactsAsyncHelper mContactsAsyncHelper;
    private final DialerCodeReceiver mDialerCodeReceiver;

    private boolean mIsBootComplete = false;

    private final BroadcastReceiver mUserSwitchedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.startSession("TSSwR.oR");
            try {
                synchronized (mLock) {
                    int userHandleId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
                    UserHandle currentUserHandle = new UserHandle(userHandleId);
                    mPhoneAccountRegistrar.setCurrentUserHandle(currentUserHandle);
                    mCallsManager.onUserSwitch(currentUserHandle);
                }
            } finally {
                Log.endSession();
            }
        }
    };

    private final BroadcastReceiver mUserStartingReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.startSession("TSStR.oR");
            try {
                synchronized (mLock) {
                    int userHandleId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
                    UserHandle addingUserHandle = new UserHandle(userHandleId);
                    mCallsManager.onUserStarting(addingUserHandle);
                }
            } finally {
                Log.endSession();
            }
        }
    };

    private final BroadcastReceiver mBootCompletedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.startSession("TSBCR.oR");
            try {
                synchronized (mLock) {
                    mIsBootComplete = true;
                    mCallsManager.onBootCompleted();
                }
            } finally {
                Log.endSession();
            }
        }
    };

    public static TelecomSystem getInstance() {
        return INSTANCE;
    }

    public static void setInstance(TelecomSystem instance) {
        if (INSTANCE != null) {
            Log.w("TelecomSystem", "Attempt to set TelecomSystem.INSTANCE twice");
        }
        Log.i(TelecomSystem.class, "TelecomSystem.INSTANCE being set");
        INSTANCE = instance;
    }

    public TelecomSystem(
            Context context,
            MissedCallNotifierImplFactory missedCallNotifierImplFactory,
            CallerInfoAsyncQueryFactory callerInfoAsyncQueryFactory,
            HeadsetMediaButtonFactory headsetMediaButtonFactory,
            ProximitySensorManagerFactory proximitySensorManagerFactory,
            InCallWakeLockControllerFactory inCallWakeLockControllerFactory,
            AudioServiceFactory audioServiceFactory,
            ConnectionServiceFocusManager.ConnectionServiceFocusManagerFactory
                    connectionServiceFocusManagerFactory,
            Timeouts.Adapter timeoutsAdapter,
            AsyncRingtonePlayer asyncRingtonePlayer,
            PhoneNumberUtilsAdapter phoneNumberUtilsAdapter,
            IncomingCallNotifier incomingCallNotifier,
            InCallTonePlayer.ToneGeneratorFactory toneGeneratorFactory,
            CallAudioRouteStateMachine.Factory callAudioRouteStateMachineFactory,
            CallAudioModeStateMachine.Factory callAudioModeStateMachineFactory,
            ClockProxy clockProxy,
            RoleManagerAdapter roleManagerAdapter,
            ContactsAsyncHelper.Factory contactsAsyncHelperFactory,
            DeviceIdleControllerAdapter deviceIdleControllerAdapter,
            Ringer.AccessibilityManagerAdapter accessibilityManagerAdapter,
            Executor asyncTaskExecutor,
            Executor asyncCallAudioTaskExecutor,
            BlockedNumbersAdapter blockedNumbersAdapter) {
        mContext = context.getApplicationContext();
        LogUtils.initLogging(mContext);
        android.telecom.Log.setLock(mLock);
        AnomalyReporter.initialize(mContext);
        DefaultDialerManagerAdapter defaultDialerAdapter =
                new DefaultDialerCache.DefaultDialerManagerAdapterImpl();

        DefaultDialerCache defaultDialerCache = new DefaultDialerCache(mContext,
                defaultDialerAdapter, roleManagerAdapter, mLock);

        Log.startSession("TS.init");
        // Wrap this in a try block to ensure session cleanup occurs in the case of error.
        try {
            mPhoneAccountRegistrar = new PhoneAccountRegistrar(mContext, mLock, defaultDialerCache,
                    packageName -> AppLabelProxy.Util.getAppLabel(
                            mContext.getPackageManager(), packageName));

            mContactsAsyncHelper = contactsAsyncHelperFactory.create(
                    new ContactsAsyncHelper.ContentResolverAdapter() {
                        @Override
                        public InputStream openInputStream(Context context, Uri uri)
                                throws FileNotFoundException {
                            return context.getContentResolver().openInputStream(uri);
                        }
                    });
            BluetoothDeviceManager bluetoothDeviceManager = new BluetoothDeviceManager(mContext,
                    mContext.getSystemService(BluetoothManager.class).getAdapter());
            BluetoothRouteManager bluetoothRouteManager = new BluetoothRouteManager(mContext, mLock,
                    bluetoothDeviceManager, new Timeouts.Adapter());
            BluetoothStateReceiver bluetoothStateReceiver = new BluetoothStateReceiver(
                    bluetoothDeviceManager, bluetoothRouteManager);
            mContext.registerReceiver(bluetoothStateReceiver, BluetoothStateReceiver.INTENT_FILTER);

            WiredHeadsetManager wiredHeadsetManager = new WiredHeadsetManager(mContext);
            SystemStateHelper systemStateHelper = new SystemStateHelper(mContext, mLock);

            mMissedCallNotifier = missedCallNotifierImplFactory
                    .makeMissedCallNotifierImpl(mContext, mPhoneAccountRegistrar,
                            defaultDialerCache,
                            deviceIdleControllerAdapter);
            DisconnectedCallNotifier.Factory disconnectedCallNotifierFactory =
                    new DisconnectedCallNotifier.Default();

            CallerInfoLookupHelper callerInfoLookupHelper =
                    new CallerInfoLookupHelper(context, callerInfoAsyncQueryFactory,
                            mContactsAsyncHelper, mLock);

            EmergencyCallHelper emergencyCallHelper = new EmergencyCallHelper(mContext,
                    defaultDialerCache, timeoutsAdapter);

            InCallControllerFactory inCallControllerFactory = new InCallControllerFactory() {
                @Override
                public InCallController create(Context context, SyncRoot lock,
                        CallsManager callsManager, SystemStateHelper systemStateProvider,
                        DefaultDialerCache defaultDialerCache, Timeouts.Adapter timeoutsAdapter,
                        EmergencyCallHelper emergencyCallHelper) {
                    return new InCallController(context, lock, callsManager, systemStateProvider,
                            defaultDialerCache, timeoutsAdapter, emergencyCallHelper,
                            new CarModeTracker(), clockProxy);
                }
            };

            CallEndpointControllerFactory callEndpointControllerFactory =
                    new CallEndpointControllerFactory() {
                @Override
                public CallEndpointController create(Context context, SyncRoot lock,
                        CallsManager callsManager) {
                    return new CallEndpointController(context, callsManager);
                }
            };

            CallDiagnosticServiceController callDiagnosticServiceController =
                    new CallDiagnosticServiceController(
                            new CallDiagnosticServiceController.ContextProxy() {
                                @Override
                                public List<ResolveInfo> queryIntentServicesAsUser(
                                        @NonNull Intent intent, int flags, int userId) {
                                    return mContext.getPackageManager().queryIntentServicesAsUser(
                                            intent, flags, userId);
                                }

                                @Override
                                public boolean bindServiceAsUser(@NonNull Intent service,
                                        @NonNull ServiceConnection conn, int flags,
                                        @NonNull UserHandle user) {
                                    return mContext.bindServiceAsUser(service, conn, flags, user);
                                }

                                @Override
                                public void unbindService(@NonNull ServiceConnection conn) {
                                    mContext.unbindService(conn);
                                }

                                @Override
                                public UserHandle getCurrentUserHandle() {
                                    return mCallsManager.getCurrentUserHandle();
                                }
                            },
                            mContext.getResources().getString(
                                    com.android.server.telecom.R.string
                                            .call_diagnostic_service_package_name),
                            mLock
                    );

            AudioProcessingNotification audioProcessingNotification =
                    new AudioProcessingNotification(mContext);

            ToastFactory toastFactory = new ToastFactory() {
                @Override
                public Toast makeText(Context context, int resId, int duration) {
                    return Toast.makeText(context, context.getMainLooper(),
                            context.getString(resId),
                            duration);
                }

                @Override
                public Toast makeText(Context context, CharSequence text, int duration) {
                    return Toast.makeText(context, context.getMainLooper(), text, duration);
                }
            };

            EmergencyCallDiagnosticLogger emergencyCallDiagnosticLogger =
                    new EmergencyCallDiagnosticLogger(mContext.getSystemService(
                            TelephonyManager.class), mContext.getSystemService(
                            BugreportManager.class), timeoutsAdapter, mContext.getSystemService(
                            DropBoxManager.class), asyncTaskExecutor, clockProxy);

            CallAnomalyWatchdog callAnomalyWatchdog = new CallAnomalyWatchdog(
                    Executors.newSingleThreadScheduledExecutor(),
                    mLock, timeoutsAdapter, clockProxy, emergencyCallDiagnosticLogger);

            TransactionManager transactionManager = TransactionManager.getInstance();

            CallStreamingNotification callStreamingNotification =
                    new CallStreamingNotification(mContext,
                            packageName -> AppLabelProxy.Util.getAppLabel(
                                    mContext.getPackageManager(), packageName), asyncTaskExecutor);

            mCallsManager = new CallsManager(
                    mContext,
                    mLock,
                    callerInfoLookupHelper,
                    mMissedCallNotifier,
                    disconnectedCallNotifierFactory,
                    mPhoneAccountRegistrar,
                    headsetMediaButtonFactory,
                    proximitySensorManagerFactory,
                    inCallWakeLockControllerFactory,
                    connectionServiceFocusManagerFactory,
                    audioServiceFactory,
                    bluetoothRouteManager,
                    wiredHeadsetManager,
                    systemStateHelper,
                    defaultDialerCache,
                    timeoutsAdapter,
                    asyncRingtonePlayer,
                    phoneNumberUtilsAdapter,
                    emergencyCallHelper,
                    toneGeneratorFactory,
                    clockProxy,
                    audioProcessingNotification,
                    bluetoothStateReceiver,
                    callAudioRouteStateMachineFactory,
                    callAudioModeStateMachineFactory,
                    inCallControllerFactory,
                    callDiagnosticServiceController,
                    roleManagerAdapter,
                    toastFactory,
                    callEndpointControllerFactory,
                    callAnomalyWatchdog,
                    accessibilityManagerAdapter,
                    asyncTaskExecutor,
                    asyncCallAudioTaskExecutor,
                    blockedNumbersAdapter,
                    transactionManager,
                    emergencyCallDiagnosticLogger,
                    callStreamingNotification);

            mIncomingCallNotifier = incomingCallNotifier;
            incomingCallNotifier.setCallsManagerProxy(new IncomingCallNotifier.CallsManagerProxy() {
                @Override
                public boolean hasUnholdableCallsForOtherConnectionService(
                        PhoneAccountHandle phoneAccountHandle) {
                    return mCallsManager.hasUnholdableCallsForOtherConnectionService(
                            phoneAccountHandle);
                }

                @Override
                public int getNumUnholdableCallsForOtherConnectionService(
                        PhoneAccountHandle phoneAccountHandle) {
                    return mCallsManager.getNumUnholdableCallsForOtherConnectionService(
                            phoneAccountHandle);
                }

                @Override
                public Call getActiveCall() {
                    return mCallsManager.getActiveCall();
                }
            });
            mCallsManager.setIncomingCallNotifier(mIncomingCallNotifier);

            mRespondViaSmsManager = new RespondViaSmsManager(mCallsManager, mLock);
            mCallsManager.setRespondViaSmsManager(mRespondViaSmsManager);

            mContext.registerReceiverAsUser(mUserSwitchedReceiver, UserHandle.ALL,
                    USER_SWITCHED_FILTER, null, null);
            mContext.registerReceiverAsUser(mUserStartingReceiver, UserHandle.ALL,
                    USER_STARTING_FILTER, null, null);
            mContext.registerReceiverAsUser(mBootCompletedReceiver, UserHandle.ALL,
                    BOOT_COMPLETE_FILTER, null, null);

            // Set current user explicitly since USER_SWITCHED_FILTER intent can be missed at
            // startup
            synchronized (mLock) {
                UserHandle currentUserHandle = UserHandle.of(ActivityManager.getCurrentUser());
                mPhoneAccountRegistrar.setCurrentUserHandle(currentUserHandle);
                mCallsManager.onUserSwitch(currentUserHandle);
            }

            mCallIntentProcessor = new CallIntentProcessor(mContext, mCallsManager,
                    defaultDialerCache);
            mTelecomBroadcastIntentProcessor = new TelecomBroadcastIntentProcessor(
                    mContext, mCallsManager);

            // Register the receiver for the dialer secret codes, used to enable extended logging.
            mDialerCodeReceiver = new DialerCodeReceiver(mCallsManager);
            mContext.registerReceiver(mDialerCodeReceiver, DIALER_SECRET_CODE_FILTER,
                    Manifest.permission.CONTROL_INCALL_EXPERIENCE, null);

            // There is no USER_SWITCHED broadcast for user 0, handle it here explicitly.
            final UserManager userManager = UserManager.get(mContext);
            mTelecomServiceImpl = new TelecomServiceImpl(
                    mContext, mCallsManager, mPhoneAccountRegistrar,
                    new CallIntentProcessor.AdapterImpl(defaultDialerCache),
                    new UserCallIntentProcessorFactory() {
                        @Override
                        public UserCallIntentProcessor create(Context context,
                                UserHandle userHandle) {
                            return new UserCallIntentProcessor(context, userHandle);
                        }
                    },
                    defaultDialerCache,
                    new TelecomServiceImpl.SubscriptionManagerAdapterImpl(),
                    new TelecomServiceImpl.SettingsSecureAdapterImpl(),
                    mLock);
        } finally {
            Log.endSession();
        }
    }

    @VisibleForTesting
    public PhoneAccountRegistrar getPhoneAccountRegistrar() {
        return mPhoneAccountRegistrar;
    }

    @VisibleForTesting
    public CallsManager getCallsManager() {
        return mCallsManager;
    }

    public CallIntentProcessor getCallIntentProcessor() {
        return mCallIntentProcessor;
    }

    public TelecomBroadcastIntentProcessor getTelecomBroadcastIntentProcessor() {
        return mTelecomBroadcastIntentProcessor;
    }

    public TelecomServiceImpl getTelecomServiceImpl() {
        return mTelecomServiceImpl;
    }

    public Object getLock() {
        return mLock;
    }

    public boolean isBootComplete() {
        return mIsBootComplete;
    }
}