FileDocCategorySizeDatePackage
BluetoothControllerImpl.javaAPI DocAndroid 5.1 API24278Thu Mar 12 22:22:42 GMT 2015com.android.systemui.statusbar.policy

BluetoothControllerImpl

public class BluetoothControllerImpl extends Object implements BluetoothController

Fields Summary
private static final String
TAG
private static final boolean
DEBUG
private static final int[]
CONNECTION_STATES
private static final int
MSG_UPDATE_CONNECTION_STATES
private static final int
MSG_UPDATE_SINGLE_CONNECTION_STATE
private static final int
MSG_UPDATE_BONDED_DEVICES
private static final int
MSG_ADD_PROFILE
private static final int
MSG_REM_PROFILE
private final android.content.Context
mContext
private final ArrayList
mCallbacks
private final android.bluetooth.BluetoothAdapter
mAdapter
private final Receiver
mReceiver
private final android.util.ArrayMap
mDeviceInfo
private final android.util.SparseArray
mProfiles
private final H
mHandler
private boolean
mEnabled
private boolean
mConnecting
private android.bluetooth.BluetoothDevice
mLastDevice
private final android.bluetooth.BluetoothProfile.ServiceListener
mProfileListener
Constructors Summary
public BluetoothControllerImpl(android.content.Context context, android.os.Looper bgLooper)


         
        mContext = context;
        mHandler = new H(bgLooper);

        final BluetoothManager bluetoothManager =
                (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        mAdapter = bluetoothManager.getAdapter();
        if (mAdapter == null) {
            Log.w(TAG, "Default BT adapter not found");
            return;
        }

        mReceiver.register();
        setAdapterState(mAdapter.getState());
        updateBondedDevices();
        bindAllProfiles();
    
Methods Summary
public voidaddStateChangedCallback(Callback cb)

        mCallbacks.add(cb);
        fireStateChange(cb);
    
private voidbindAllProfiles()

        // Note: This needs to contain all of the types that can be returned by BluetoothUtil
        // otherwise we can't find the profiles we need when we connect/disconnect.
        mAdapter.getProfileProxy(mContext, mProfileListener, BluetoothProfile.A2DP);
        mAdapter.getProfileProxy(mContext, mProfileListener, BluetoothProfile.A2DP_SINK);
        mAdapter.getProfileProxy(mContext, mProfileListener, BluetoothProfile.AVRCP_CONTROLLER);
        mAdapter.getProfileProxy(mContext, mProfileListener, BluetoothProfile.HEADSET);
        mAdapter.getProfileProxy(mContext, mProfileListener, BluetoothProfile.HEADSET_CLIENT);
        mAdapter.getProfileProxy(mContext, mProfileListener, BluetoothProfile.INPUT_DEVICE);
        mAdapter.getProfileProxy(mContext, mProfileListener, BluetoothProfile.MAP);
        mAdapter.getProfileProxy(mContext, mProfileListener, BluetoothProfile.PAN);
        // Note Health is not in this list because health devices aren't 'connected'.
        // If profiles are expanded to use more than just connection state and connect/disconnect
        // then it should be added.
    
public voidconnect(PairedDevice pd)

        connect(pd, true);
    
private voidconnect(PairedDevice pd, boolean connect)

        if (mAdapter == null || pd == null || pd.tag == null) return;
        final BluetoothDevice device = (BluetoothDevice) pd.tag;
        final DeviceInfo info = mDeviceInfo.get(device);
        final String action = connect ? "connect" : "disconnect";
        if (DEBUG) Log.d(TAG, action + " " + deviceToString(device));
        final ParcelUuid[] uuids = device.getUuids();
        if (uuids == null) {
            Log.w(TAG, "No uuids returned, aborting " + action + " for " + deviceToString(device));
            return;
        }
        SparseArray<Boolean> profiles = new SparseArray<>();
        if (connect) {
            // When connecting add every profile we can recognize by uuid.
            for (ParcelUuid uuid : uuids) {
                final int profile = uuidToProfile(uuid);
                if (profile == 0) {
                    Log.w(TAG, "Device " + deviceToString(device) + " has an unsupported uuid: "
                            + uuidToString(uuid));
                    continue;
                }
                final boolean connected = info.connectedProfiles.get(profile, false);
                if (!connected) {
                    profiles.put(profile, true);
                }
            }
        } else {
            // When disconnecting, just add every profile we know they are connected to.
            profiles = info.connectedProfiles;
        }
        for (int i = 0; i < profiles.size(); i++) {
            final int profile = profiles.keyAt(i);
            if (mProfiles.indexOfKey(profile) >= 0) {
                final Profile p = BluetoothUtil.getProfile(mProfiles.get(profile));
                final boolean ok = connect ? p.connect(device) : p.disconnect(device);
                if (DEBUG) Log.d(TAG, action + " " + profileToString(profile) + " "
                        + (ok ? "succeeded" : "failed"));
            } else {
                Log.w(TAG, "Unable get get Profile for " + profileToString(profile));
            }
        }
    
private static intconnectionStateToPairedDeviceState(int index)

        int state = CONNECTION_STATES[index];
        if (state == BluetoothAdapter.STATE_CONNECTED) return PairedDevice.STATE_CONNECTED;
        if (state == BluetoothAdapter.STATE_CONNECTING) return PairedDevice.STATE_CONNECTING;
        if (state == BluetoothAdapter.STATE_DISCONNECTING) return PairedDevice.STATE_DISCONNECTING;
        return PairedDevice.STATE_DISCONNECTED;
    
public voiddisconnect(PairedDevice pd)

        connect(pd, false);
    
public voiddump(java.io.FileDescriptor fd, java.io.PrintWriter pw, java.lang.String[] args)

        pw.println("BluetoothController state:");
        pw.print("  mAdapter="); pw.println(mAdapter);
        pw.print("  mEnabled="); pw.println(mEnabled);
        pw.print("  mConnecting="); pw.println(mConnecting);
        pw.print("  mLastDevice="); pw.println(mLastDevice);
        pw.print("  mCallbacks.size="); pw.println(mCallbacks.size());
        pw.print("  mProfiles="); pw.println(profilesToString(mProfiles));
        pw.print("  mDeviceInfo.size="); pw.println(mDeviceInfo.size());
        for (int i = 0; i < mDeviceInfo.size(); i++) {
            final BluetoothDevice device = mDeviceInfo.keyAt(i);
            final DeviceInfo info = mDeviceInfo.valueAt(i);
            pw.print("    "); pw.print(deviceToString(device));
            pw.print('("); pw.print(uuidsToString(device)); pw.print(')");
            pw.print("    "); pw.println(infoToString(info));
        }
    
private voidfirePairedDevicesChanged()

        for (Callback cb : mCallbacks) {
            cb.onBluetoothPairedDevicesChanged();
        }
    
private voidfireStateChange()

        for (Callback cb : mCallbacks) {
            fireStateChange(cb);
        }
    
private voidfireStateChange(Callback cb)

        cb.onBluetoothStateChange(mEnabled, mConnecting);
    
public java.lang.StringgetLastDeviceName()

        return mLastDevice != null ? mLastDevice.getAliasName() : null;
    
public android.util.ArraySetgetPairedDevices()

        final ArraySet<PairedDevice> rt = new ArraySet<>();
        for (int i = 0; i < mDeviceInfo.size(); i++) {
            final BluetoothDevice device = mDeviceInfo.keyAt(i);
            final DeviceInfo info = mDeviceInfo.valueAt(i);
            if (!info.bonded) continue;
            final PairedDevice paired = new PairedDevice();
            paired.id = device.getAddress();
            paired.tag = device;
            paired.name = device.getAliasName();
            paired.state = connectionStateToPairedDeviceState(info.connectionStateIndex);
            rt.add(paired);
        }
        return rt;
    
private static intgetProfileFromAction(java.lang.String action)

        if (BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
            return BluetoothProfile.A2DP;
        } else if (BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
            return BluetoothProfile.HEADSET;
        } else if (BluetoothA2dpSink.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
            return BluetoothProfile.A2DP_SINK;
        } else if (BluetoothHeadsetClient.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
            return BluetoothProfile.HEADSET_CLIENT;
        } else if (BluetoothInputDevice.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
            return BluetoothProfile.INPUT_DEVICE;
        } else if (BluetoothMap.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
            return BluetoothProfile.MAP;
        } else if (BluetoothPan.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
            return BluetoothProfile.PAN;
        }
        if (DEBUG) Log.d(TAG, "Unknown action " + action);
        return -1;
    
private voidhandleConnectionChange()

        // If we are no longer connected to the current device, see if we are connected to
        // something else, so we don't display a name we aren't connected to.
        if (mLastDevice != null &&
                CONNECTION_STATES[mDeviceInfo.get(mLastDevice).connectionStateIndex]
                        != BluetoothProfile.STATE_CONNECTED) {
            // Make sure we don't keep this device while it isn't connected.
            mLastDevice = null;
            // Look for anything else connected.
            final int size = mDeviceInfo.size();
            for (int i = 0; i < size; i++) {
                BluetoothDevice device = mDeviceInfo.keyAt(i);
                DeviceInfo info = mDeviceInfo.valueAt(i);
                if (CONNECTION_STATES[info.connectionStateIndex]
                        == BluetoothProfile.STATE_CONNECTED) {
                    mLastDevice = device;
                    break;
                }
            }
        }
    
private voidhandleUpdateBondedDevices()

        if (mAdapter == null) return;
        final Set<BluetoothDevice> bondedDevices = mAdapter.getBondedDevices();
        for (DeviceInfo info : mDeviceInfo.values()) {
            info.bonded = false;
        }
        int bondedCount = 0;
        BluetoothDevice lastBonded = null;
        if (bondedDevices != null) {
            for (BluetoothDevice bondedDevice : bondedDevices) {
                final boolean bonded = bondedDevice.getBondState() != BluetoothDevice.BOND_NONE;
                updateInfo(bondedDevice).bonded = bonded;
                if (bonded) {
                    bondedCount++;
                    lastBonded = bondedDevice;
                }
            }
        }
        if (mLastDevice == null && bondedCount == 1) {
            mLastDevice = lastBonded;
        }
        updateConnectionStates();
        firePairedDevicesChanged();
    
private voidhandleUpdateConnectionState(android.bluetooth.BluetoothDevice device, int profile, int state)

        if (DEBUG) Log.d(TAG, "updateConnectionState " + BluetoothUtil.deviceToString(device)
                + " " + BluetoothUtil.profileToString(profile)
                + " " + BluetoothUtil.connectionStateToString(state));
        DeviceInfo info = updateInfo(device);
        int stateIndex = 0;
        for (int i = 0; i < CONNECTION_STATES.length; i++) {
            if (CONNECTION_STATES[i] == state) {
                stateIndex = i;
                break;
            }
        }
        info.profileStates.put(profile, stateIndex);

        info.connectionStateIndex = 0;
        final int N = info.profileStates.size();
        for (int i = 0; i < N; i++) {
            if (info.profileStates.valueAt(i) > info.connectionStateIndex) {
                info.connectionStateIndex = info.profileStates.valueAt(i);
            }
        }
        if (state == BluetoothProfile.STATE_CONNECTED) {
            info.connectedProfiles.put(profile, true);
        } else {
            info.connectedProfiles.remove(profile);
        }
    
private voidhandleUpdateConnectionStates()

        final int N = mDeviceInfo.size();
        for (int i = 0; i < N; i++) {
            BluetoothDevice device = mDeviceInfo.keyAt(i);
            DeviceInfo info = updateInfo(device);
            info.connectionStateIndex = 0;
            info.connectedProfiles.clear();
            for (int j = 0; j < mProfiles.size(); j++) {
                int state = mProfiles.valueAt(j).getConnectionState(device);
                handleUpdateConnectionState(device, mProfiles.keyAt(j), state);
            }
        }
        handleConnectionChange();
        firePairedDevicesChanged();
    
private static java.lang.StringinfoToString(com.android.systemui.statusbar.policy.BluetoothControllerImpl$DeviceInfo info)

        return info == null ? null : ("connectionState=" +
                connectionStateToString(CONNECTION_STATES[info.connectionStateIndex])
                + ",bonded=" + info.bonded + ",profiles="
                + profilesToString(info.connectedProfiles));
    
public booleanisBluetoothConnected()

        return mAdapter != null
                && mAdapter.getConnectionState() == BluetoothAdapter.STATE_CONNECTED;
    
public booleanisBluetoothConnecting()

        return mAdapter != null
                && mAdapter.getConnectionState() == BluetoothAdapter.STATE_CONNECTING;
    
public booleanisBluetoothEnabled()

        return mAdapter != null && mAdapter.isEnabled();
    
public booleanisBluetoothSupported()

        return mAdapter != null;
    
private static java.lang.StringprofilesToString(android.util.SparseArray profiles)

        final int N = profiles.size();
        final StringBuffer buffer = new StringBuffer();
        buffer.append('[");
        for (int i = 0; i < N; i++) {
            if (i != 0) {
                buffer.append(',");
            }
            buffer.append(BluetoothUtil.profileToString(profiles.keyAt(i)));
        }
        buffer.append(']");
        return buffer.toString();
    
public voidremoveStateChangedCallback(Callback cb)

        mCallbacks.remove(cb);
    
private voidsetAdapterState(int adapterState)

        final boolean enabled = adapterState == BluetoothAdapter.STATE_ON;
        if (mEnabled == enabled) return;
        mEnabled = enabled;
        fireStateChange();
    
public voidsetBluetoothEnabled(boolean enabled)

        if (mAdapter != null) {
            if (enabled) {
                mAdapter.enable();
            } else {
                mAdapter.disable();
            }
        }
    
private voidsetConnecting(boolean connecting)

        if (mConnecting == connecting) return;
        mConnecting = connecting;
        fireStateChange();
    
private voidupdateBondedDevices()

        mHandler.removeMessages(MSG_UPDATE_BONDED_DEVICES);
        mHandler.sendEmptyMessage(MSG_UPDATE_BONDED_DEVICES);
    
private voidupdateConnectionState(android.bluetooth.BluetoothDevice device, int profile, int state)

        if (mHandler.hasMessages(MSG_UPDATE_CONNECTION_STATES)) {
            // If we are about to update all the devices, then we don't need to update this one.
            return;
        }
        mHandler.obtainMessage(MSG_UPDATE_SINGLE_CONNECTION_STATE, profile, state, device)
                .sendToTarget();
    
private voidupdateConnectionStates()

        mHandler.removeMessages(MSG_UPDATE_CONNECTION_STATES);
        mHandler.removeMessages(MSG_UPDATE_SINGLE_CONNECTION_STATE);
        mHandler.sendEmptyMessage(MSG_UPDATE_CONNECTION_STATES);
    
private com.android.systemui.statusbar.policy.BluetoothControllerImpl$DeviceInfoupdateInfo(android.bluetooth.BluetoothDevice device)

        DeviceInfo info = mDeviceInfo.get(device);
        info = info != null ? info : new DeviceInfo();
        mDeviceInfo.put(device, info);
        return info;