summaryrefslogtreecommitdiff
path: root/Settings/src/com/android/tv/settings/accessories/BluetoothDevicePairer.java
blob: 3b816a77d98ae0da68efb2afadb7622835d3e1ff (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
/*
 * 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.tv.settings.accessories;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.hardware.input.InputManager;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.InputDevice;

import com.android.tv.settings.util.bluetooth.BluetoothDeviceCriteria;
import com.android.tv.settings.util.bluetooth.BluetoothScanner;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * Monitors available Bluetooth devices and manages process of pairing
 * and connecting to the device.
 */
public class BluetoothDevicePairer {

    /**
     * This class operates in two modes, automatic and manual.
     *
     * AUTO MODE
     * In auto mode we listen for an input device that looks like it can
     * generate DPAD events. When one is found we wait
     * {@link #DELAY_AUTO_PAIRING} milliseconds before starting the process of
     * connecting to the device. The idea is that a UI making use of this class
     * would give the user a chance to cancel pairing during this window. Once
     * the connection process starts, it is considered uninterruptible.
     *
     * Connection is accomplished in two phases, bonding and socket connection.
     * First we try to create a bond to the device and listen for bond status
     * change broadcasts. Once the bond is made, we connect to the device.
     * Connecting to the device actually opens a socket and hooks the device up
     * to the input system.
     *
     * In auto mode if we see more than one compatible input device before
     * bonding with a candidate device, we stop the process. We don't want to
     * connect to the wrong device and it is up to the user of this class to
     * tell us what to connect to.
     *
     * MANUAL MODE
     * Manual mode is where a user of this class explicitly tells us which
     * device to connect to. To switch to manual mode you can call
     * {@link #cancelPairing()}. It is safe to call this method even if no
     * device connection process is underway. You would then call
     * {@link #start()} to resume scanning for devices. Once one is found
     * that you want to connect to, call {@link #startPairing(BluetoothDevice)}
     * to start the connection process. At this point the same process is
     * followed as when we start connection in auto mode.
     *
     * Even in manual mode there is a timeout before we actually start
     * connecting, but it is {@link #DELAY_MANUAL_PAIRING}.
     */

    public static final String TAG = "BluetoothDevicePairer";
    public static final int STATUS_ERROR = -1;
    public static final int STATUS_NONE = 0;
    public static final int STATUS_SCANNING = 1;
    /**
     * A device to pair with has been identified, we're currently in the
     * timeout period where the process can be cancelled.
     */
    public static final int STATUS_WAITING_TO_PAIR = 2;
    /**
     * Pairing is in progress.
     */
    public static final int STATUS_PAIRING = 3;
    /**
     * Device has been paired with, we are opening a connection to the device.
     */
    public static final int STATUS_CONNECTING = 4;
    /**
     * BR/EDR mice need to be handled separately because of the unique
     * connection establishment sequence.
     */
    public static final int STATUS_SUCCEED_BREDRMOUSE = 5;


    public interface EventListener {
        /**
         * The status of the {@link BluetoothDevicePairer} changed.
         */
        void statusChanged();
    }

    public interface BluetoothConnector {
        void openConnection(BluetoothAdapter adapter);
    }

    public interface OpenConnectionCallback {
        /**
         * Call back when BT device connection is completed.
         */
        void succeeded();
        void failed();
    }

    /**
     * Time between when a single input device is found and pairing begins. If
     * one or more other input devices are found before this timeout or
     * {@link #cancelPairing()} is called then pairing will not proceed.
     */
    public static final int DELAY_AUTO_PAIRING = 15 * 1000;
    /**
     * Time between when the call to {@link #startPairing(BluetoothDevice)} is
     * called and when we actually start pairing. This gives the caller a
     * chance to change their mind.
     */
    public static final int DELAY_MANUAL_PAIRING = 5 * 1000;
    /**
     * If there was an error in pairing, we will wait this long before trying
     * again.
     */
    public static final int DELAY_RETRY = 5 * 1000;

    private static final int MSG_PAIR = 1;
    private static final int MSG_START = 2;

    private static final boolean DEBUG = true;

    private static final String[] INVALID_INPUT_KEYBOARD_DEVICE_NAMES = {
        "gpio-keypad", "cec_keyboard", "Virtual", "athome_remote"
    };

    private static final int SCAN_MODE_NOT_SET = 0;

    private final BluetoothScanner.Listener mBtListener = new BluetoothScanner.Listener() {
        @Override
        public void onDeviceAdded(BluetoothScanner.Device device) {
            if (DEBUG) {
                Log.d(TAG, "Adding device: " + device.btDevice.getAddress());
            }
            onDeviceFound(device.btDevice);
        }

        @Override
        public void onDeviceRemoved(BluetoothScanner.Device device) {
            if (DEBUG) {
                Log.d(TAG, "Device lost: " + device.btDevice.getAddress());
            }
            onDeviceLost(device.btDevice);
        }
    };

    public static boolean hasValidInputDevice(Context context, int[] deviceIds) {
        InputManager inMan = (InputManager) context.getSystemService(Context.INPUT_SERVICE);

        for (int ptr = deviceIds.length - 1; ptr > -1; ptr--) {
            InputDevice device = inMan.getInputDevice(deviceIds[ptr]);
            int sources = device.getSources();

            boolean isCompatible = false;

            if ((sources & InputDevice.SOURCE_DPAD) == InputDevice.SOURCE_DPAD) {
                isCompatible = true;
            }

            if ((sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) {
                isCompatible = true;
            }

            if ((sources & InputDevice.SOURCE_MOUSE) == InputDevice.SOURCE_MOUSE) {
                isCompatible = true;
            }

            if ((sources & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) {
                isCompatible = true;
            }

            if ((sources & InputDevice.SOURCE_KEYBOARD) == InputDevice.SOURCE_KEYBOARD) {
                boolean isValidKeyboard = true;
                String keyboardName = device.getName();
                for (int index = 0; index < INVALID_INPUT_KEYBOARD_DEVICE_NAMES.length; ++index) {
                    if (keyboardName.equals(INVALID_INPUT_KEYBOARD_DEVICE_NAMES[index])) {
                        isValidKeyboard = false;
                        break;
                    }
                }

                if (isValidKeyboard) {
                    isCompatible = true;
                }
            }

            if (!device.isVirtual() && isCompatible) {
                return true;
            }
        }
        return false;
    }

    public static boolean hasValidInputDevice(Context context) {
        InputManager inMan = (InputManager) context.getSystemService(Context.INPUT_SERVICE);
        int[] inputDevices = inMan.getInputDeviceIds();

        return hasValidInputDevice(context, inputDevices);
    }

    private final BroadcastReceiver mLinkStatusReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (DEBUG) {
                Log.d(TAG, "There was a link status change for: " + device.getAddress());
            }

            if (device.equals(mTarget)) {
                int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,
                        BluetoothDevice.BOND_NONE);
                int previousBondState = intent.getIntExtra(
                        BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.BOND_NONE);

                if (DEBUG) {
                    Log.d(TAG, "Bond states: old = " + previousBondState + ", new = " +
                        bondState);
                }

                if (bondState == BluetoothDevice.BOND_NONE &&
                        previousBondState == BluetoothDevice.BOND_BONDING) {
                    // we seem to have reverted, this is an error
                    // TODO inform user, start scanning again
                    unregisterLinkStatusReceiver();
                    onBondFailed();
                } else if (bondState == BluetoothDevice.BOND_BONDED) {
                    unregisterLinkStatusReceiver();
                    onBonded();
                }
            }
        }
    };

    private BroadcastReceiver mBluetoothStateReceiver;

    private final OpenConnectionCallback mOpenConnectionCallback = new OpenConnectionCallback() {
        public void succeeded() {
            setStatus(STATUS_NONE);
        }
        public void failed() {
            setStatus(STATUS_ERROR);
        }
    };

    private final Context mContext;
    private EventListener mListener;
    private int mStatus = STATUS_NONE;
    /**
     * Set to {@code false} when {@link #cancelPairing()} or
     * {@link #startPairing(BluetoothDevice)}. This instance
     * will now no longer automatically start pairing.
     */
    private boolean mAutoMode = true;
    private final ArrayList<BluetoothDevice> mVisibleDevices = new ArrayList<>();
    private BluetoothDevice mTarget;
    private final Handler mHandler;
    private long mNextStageTimestamp = -1;
    private boolean mLinkReceiverRegistered = false;
    private final ArrayList<BluetoothDeviceCriteria> mBluetoothDeviceCriteria = new ArrayList<>();
    private InputDeviceCriteria mInputDeviceCriteria;
    private int mDefaultScanMode = SCAN_MODE_NOT_SET;

    /**
     * Should be instantiated on a thread with a Looper, perhaps the main thread!
     */
    public BluetoothDevicePairer(Context context, EventListener listener) {
        mContext = context.getApplicationContext();
        mListener = listener;

        addBluetoothDeviceCriteria();

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MSG_PAIR:
                        startBonding();
                        break;
                    case MSG_START:
                        start();
                        break;
                    default:
                        Log.d(TAG, "No handler case available for message: " + msg.what);
                }
            }
        };
    }

    private void addBluetoothDeviceCriteria() {
        // Input is supported by all devices.
        mInputDeviceCriteria = new InputDeviceCriteria();
        mBluetoothDeviceCriteria.add(mInputDeviceCriteria);

        // Add Bluetooth a2dp on if the service is running and the
        // setting profile_supported_a2dp is set to true.
        Intent intent = new Intent("android.bluetooth.IBluetoothA2dp");
        ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
        if (comp != null) {
            int enabledState = mContext.getPackageManager().getComponentEnabledSetting(comp);
            if (enabledState != PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                Log.d(TAG, "Adding A2dp device criteria for pairing");
                mBluetoothDeviceCriteria.add(new A2dpDeviceCriteria());
            }
        }
    }

    /**
     * Start listening for devices and begin the pairing process when
     * criteria is met.
     */
    public void start() {
        final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            Log.d(TAG, "Bluetooth not enabled, delaying startup.");
            if (mBluetoothStateReceiver == null) {
                mBluetoothStateReceiver = new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                                BluetoothAdapter.STATE_OFF) == BluetoothAdapter.STATE_ON) {
                            Log.d(TAG, "Bluetooth now enabled, starting.");
                            start();
                        } else {
                            Log.d(TAG, "Bluetooth not yet started, got broadcast: " + intent);
                        }
                    }
                };
                mContext.registerReceiver(mBluetoothStateReceiver,
                        new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
            }

            bluetoothAdapter.enable();
            return;
        } else {
            if (mBluetoothStateReceiver != null) {
                mContext.unregisterReceiver(mBluetoothStateReceiver);
                mBluetoothStateReceiver = null;
            }
        }

        // Another device may initiate pairing. To accommodate this, turn on discoverability
        // if it isn't already.
        final int scanMode = bluetoothAdapter.getScanMode();
        if (scanMode != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Log.d(TAG, "Turning on discoverability, default scan mode: " + scanMode);
            mDefaultScanMode = scanMode;
            // Remove discoverable timeout.
            bluetoothAdapter.setDiscoverableTimeout(Duration.ZERO);
            bluetoothAdapter.setScanMode(
                    BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE);
        }

        // set status to scanning before we start listening since
        // startListening may result in a transition to STATUS_WAITING_TO_PAIR
        // which might seem odd from a client perspective
        setStatus(STATUS_SCANNING);

        BluetoothScanner.startListening(mContext, mBtListener, mBluetoothDeviceCriteria);
    }

    public void clearDeviceList() {
        doCancel();
        mVisibleDevices.clear();
    }

    /**
     * Stop any pairing request that is in progress.
     */
    public void cancelPairing() {
        mAutoMode = false;
        doCancel();
    }


    /**
     * Switch to manual pairing mode.
     */
    public void disableAutoPairing() {
        mAutoMode = false;
    }

    /**
     * Stop doing anything we're doing, release any resources.
     */
    public void dispose() {
        final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mDefaultScanMode != SCAN_MODE_NOT_SET
                && mDefaultScanMode != bluetoothAdapter.getScanMode()) {
            Log.d(TAG, "Resetting discoverability to: " + mDefaultScanMode);
            bluetoothAdapter.setScanMode(mDefaultScanMode);
        }

        mHandler.removeCallbacksAndMessages(null);
        if (mLinkReceiverRegistered) {
            unregisterLinkStatusReceiver();
        }
        if (mBluetoothStateReceiver != null) {
            mContext.unregisterReceiver(mBluetoothStateReceiver);
        }
        stopScanning();
    }

    /**
     * Start pairing and connection to the specified device.
     * @param device device
     */
    public void startPairing(BluetoothDevice device) {
        startPairing(device, true);
    }

    /**
     * Return our state
     * @return One of the STATE_ constants.
     */
    public int getStatus() {
        return mStatus;
    }

    /**
     * Get the device that we're currently targeting. This will be null if
     * there is no device that is in the process of being connected to.
     */
    public BluetoothDevice getTargetDevice() {
        return mTarget;
    }

    /**
     * When the timer to start the next stage will expire, in {@link SystemClock#elapsedRealtime()}.
     * Will only be valid while waiting to pair and after an error from which we are restarting.
     */
    public long getNextStageTime() {
        return mNextStageTimestamp;
    }

    public List<BluetoothDevice> getAvailableDevices() {
        ArrayList<BluetoothDevice> copy = new ArrayList<>(mVisibleDevices.size());
        copy.addAll(mVisibleDevices);
        return copy;
    }

    public void setListener(EventListener listener) {
        mListener = listener;
    }

    public void invalidateDevice(BluetoothDevice device) {
        onDeviceLost(device);
    }

    private void startPairing(BluetoothDevice device, boolean isManual) {
        // TODO check if we're already paired/bonded to this device

        // cancel auto-mode if applicable
        mAutoMode = !isManual;

        mTarget = device;

        if (isInProgress()) {
            throw new RuntimeException("Pairing already in progress, you must cancel the " +
                    "previous request first");
        }

        mHandler.removeCallbacksAndMessages(null);

        mNextStageTimestamp = SystemClock.elapsedRealtime() +
                (mAutoMode ? DELAY_AUTO_PAIRING : DELAY_MANUAL_PAIRING);
        mHandler.sendEmptyMessageDelayed(MSG_PAIR,
                mAutoMode ? DELAY_AUTO_PAIRING : DELAY_MANUAL_PAIRING);

        setStatus(STATUS_WAITING_TO_PAIR);
    }

    /**
     * Pairing is in progress and is no longer cancelable.
     */
    public boolean isInProgress() {
        return mStatus != STATUS_NONE && mStatus != STATUS_ERROR && mStatus != STATUS_SCANNING &&
                mStatus != STATUS_WAITING_TO_PAIR;
    }

    private void updateListener() {
        if (mListener != null) {
            mListener.statusChanged();
        }
    }

    private void onDeviceFound(BluetoothDevice device) {
        if (!mVisibleDevices.contains(device)) {
            mVisibleDevices.add(device);
            Log.d(TAG, "Added device to visible list. Name = " + device.getName() + " , class = " +
                    device.getBluetoothClass().getDeviceClass());
        } else {
            return;
        }

        updatePairingState();
        // update the listener because a new device is visible
        updateListener();
    }

    private void onDeviceLost(BluetoothDevice device) {
        // TODO validate removal works as expected
        if (mVisibleDevices.remove(device)) {
            updatePairingState();
            // update the listener because a device disappeared
            updateListener();
        }
    }

    private void updatePairingState() {
        if (mAutoMode) {
            BluetoothDevice candidate = getAutoPairDevice();
            if (null != candidate) {
                mTarget = candidate;
                startPairing(mTarget, false);
            } else {
                doCancel();
            }
        }
    }

    /**
     * @return returns the only visible input device if there is only one
     */
    private BluetoothDevice getAutoPairDevice() {
        List<BluetoothDevice> inputDevices = new ArrayList<>();
        for (BluetoothDevice device : mVisibleDevices) {
            if (mInputDeviceCriteria.isInputDevice(device.getBluetoothClass())) {
                inputDevices.add(device);
            }
        }
        if (inputDevices.size() == 1) {
            return inputDevices.get(0);
        }
        return null;
    }

    private void doCancel() {
        // TODO allow cancel to be called from any state
        if (isInProgress()) {
            Log.d(TAG, "Pairing process has already begun, it can not be canceled.");
            return;
        }

        // stop scanning, just in case we are
        final boolean wasListening = BluetoothScanner.stopListening(mBtListener);
        BluetoothScanner.stopNow();

        mHandler.removeCallbacksAndMessages(null);

        // remove bond, if existing
        unpairDevice(mTarget);

        mTarget = null;

        setStatus(STATUS_NONE);

        // resume scanning
        if (wasListening) {
            start();
        }
    }

    /**
     * Set the status and update any listener.
     */
    private void setStatus(int status) {
        mStatus = status;
        updateListener();
    }

    private void startBonding() {
        stopScanning();
        setStatus(STATUS_PAIRING);
        if (mTarget.getBondState() != BluetoothDevice.BOND_BONDED) {
            registerLinkStatusReceiver();

            // create bond (pair) to the device
            mTarget.createBond();
        } else {
            onBonded();
        }
    }

    private void onBonded() {
        BluetoothDevice target = getTargetDevice();
        if (!(target.getBluetoothClass().getDeviceClass()
                    == BluetoothClass.Device.PERIPHERAL_POINTING)
                || !(target.getType() == BluetoothDevice.DEVICE_TYPE_CLASSIC)) {
            openConnection();
        } else if (target.isConnected()) {
            setStatus(STATUS_SUCCEED_BREDRMOUSE);
        } else {
            Log.w(TAG, "There was an error connect by BR/EDR Mouse.");
            setStatus(STATUS_ERROR);
        }
    }

    private void openConnection() {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        BluetoothConnector btConnector = getBluetoothConnector();
        if (btConnector != null) {
            setStatus(STATUS_CONNECTING);
            btConnector.openConnection(adapter);
        } else {
            Log.w(TAG, "There was an error getting the BluetoothConnector.");
            setStatus(STATUS_ERROR);
            if (mLinkReceiverRegistered) {
                unregisterLinkStatusReceiver();
            }
            unpairDevice(mTarget);
        }
    }

    private void onBondFailed() {
        Log.w(TAG, "There was an error bonding with the device.");
        setStatus(STATUS_ERROR);

        // remove bond, if existing
        unpairDevice(mTarget);

        // TODO do we need to check Bluetooth for the device and possible delete it?
        mNextStageTimestamp = SystemClock.elapsedRealtime() + DELAY_RETRY;
        mHandler.sendEmptyMessageDelayed(MSG_START, DELAY_RETRY);
    }

    private void registerLinkStatusReceiver() {
        mLinkReceiverRegistered = true;
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        mContext.registerReceiver(mLinkStatusReceiver, filter);
    }

    private void unregisterLinkStatusReceiver() {
        mLinkReceiverRegistered = false;
        mContext.unregisterReceiver(mLinkStatusReceiver);
    }

    private void stopScanning() {
        BluetoothScanner.stopListening(mBtListener);
        BluetoothScanner.stopNow();
    }

    public boolean unpairDevice(BluetoothDevice device) {
        if (device != null) {
            int state = device.getBondState();

            if (state == BluetoothDevice.BOND_BONDING) {
                device.cancelBondProcess();
            }

            if (state != BluetoothDevice.BOND_NONE) {
                final boolean successful = device.removeBond();
                if (successful) {
                    if (DEBUG) {
                        Log.d(TAG, "Bluetooth device successfully unpaired: " + device.getName());
                    }
                    return true;
                } else {
                    Log.e(TAG, "Failed to unpair Bluetooth Device: " + device.getName());
                }
            }
        }
        return false;
    }

    private BluetoothConnector getBluetoothConnector() {
        int majorDeviceClass = mTarget.getBluetoothClass().getMajorDeviceClass();
        switch (majorDeviceClass) {
            case BluetoothClass.Device.Major.PERIPHERAL:
                return new BluetoothInputDeviceConnector(
                    mContext, mTarget, mHandler, mOpenConnectionCallback);
            case BluetoothClass.Device.Major.AUDIO_VIDEO:
                return new BluetoothA2dpConnector(mContext, mTarget, mOpenConnectionCallback);
            default:
                Log.d(TAG, "Unhandle device class: " + majorDeviceClass);
                break;
        }
        return null;
    }
}