summaryrefslogtreecommitdiff
path: root/libraries/BluetoothServices/src/com/google/android/tv/btservices/BluetoothUtils.java
blob: 439b3e3c0b2f0ad37920045fa2a1242efe3fce35 (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
/*
 * Copyright (C) 2021 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.google.android.tv.btservices;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.util.Log;

import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.bluetooth.LocalBluetoothManager;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class BluetoothUtils {

    private static final String TAG = "Atv.BluetoothUtils";

    private static List<String> sKnownRemoteLabels = null;
    private static final int MINOR_MASK = 0b11111100;

    private static final int MINOR_DEVICE_CLASS_POINTING = 0b10000000;
    private static final int MINOR_DEVICE_CLASS_KEYBOARD = 0b01000000;
    private static final int MINOR_DEVICE_CLASS_JOYSTICK = 0b00000100;
    private static final int MINOR_DEVICE_CLASS_GAMEPAD = 0b00001000;
    private static final int MINOR_DEVICE_CLASS_REMOTE = 0b00001100;

    // Includes any generic keyboards or pointers, and any joystick, game pad, or remote subtypes.
    private static final int MINOR_REMOTE_MASK = 0b11001100;

    public static boolean isRemoteClass(BluetoothDevice device) {
        if (device == null) {
            return false;
        }
        int major = device.getBluetoothClass().getMajorDeviceClass();
        int minor = device.getBluetoothClass().getDeviceClass() & MINOR_MASK;
        return BluetoothClass.Device.Major.PERIPHERAL == major
            && (minor & ~MINOR_REMOTE_MASK) == 0;
    }

    private static void setKnownRemoteLabels(Context context) {
        if (context == null) {
            return;
        }
        sKnownRemoteLabels = Collections.unmodifiableList(Arrays.asList(
                context.getResources().getStringArray(R.array.known_bluetooth_device_labels)));
        // For backward compatibility, the customization name used to be known_remote_labels
        if (sKnownRemoteLabels.isEmpty()) {
            sKnownRemoteLabels = Collections.unmodifiableList(
                    Arrays.asList(
                        context.getResources().getStringArray(
                            R.array.known_remote_labels)));
        }
    }

    public static boolean isConnected(BluetoothDevice device) {
        if (device == null) {
            return false;
        }
        return device.getBondState() == BluetoothDevice.BOND_BONDED && device.isConnected();
    }

    public static boolean isBonded(BluetoothDevice device) {
        if (device == null) {
            return false;
        }
        return device.getBondState() == BluetoothDevice.BOND_BONDED && !device.isConnected();
    }

    public static String getName(BluetoothDevice device) {
        if (device == null) {
            return null;
        }
        return device.getAlias() != null ? device.getAlias() : device.getName();
    }

    public static String getOriginalName(BluetoothDevice device) {
        if (device == null) {
            return null;
        }
        return device.getName();
    }

    public static boolean isRemote(Context context, BluetoothDevice device) {
        if (sKnownRemoteLabels == null) {
            setKnownRemoteLabels(context);
        }
        if (device == null) {
            return false;
        }
        if (device.getName() == null) {
            return false;
        }

        if (sKnownRemoteLabels == null) {
            return false;
        }

        final String name = device.getName().toLowerCase();
        for (String knownLabel: sKnownRemoteLabels) {
            if (name.contains(knownLabel)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isBluetoothHeadset(BluetoothDevice device) {
        if (device == null) {
            return false;
        }
        final BluetoothClass bluetoothClass = device.getBluetoothClass();
        final int devClass = bluetoothClass.getDeviceClass();
        return (devClass == BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET ||
                devClass == BluetoothClass.Device.AUDIO_VIDEO_HEADPHONES ||
                devClass == BluetoothClass.Device.AUDIO_VIDEO_LOUDSPEAKER ||
                devClass == BluetoothClass.Device.AUDIO_VIDEO_PORTABLE_AUDIO ||
                devClass == BluetoothClass.Device.AUDIO_VIDEO_HIFI_AUDIO);
    }

    public static boolean isLeCompatible(BluetoothDevice device) {
        return device != null && (device.getType() == BluetoothDevice.DEVICE_TYPE_LE ||
                device.getType() == BluetoothDevice.DEVICE_TYPE_DUAL);
    }

    @SuppressLint("NewApi") // Hidden API made public
    public static boolean isA2dpSource(BluetoothDevice device) {
        return device != null && device.getBluetoothClass() != null &&
                device.getBluetoothClass().doesClassMatch(BluetoothProfile.A2DP);
    }

    /**
     * Match a device's metadata against a predefined list to determine whether the device is an
     * official device to be used with the host device.
     */
    public static boolean isOfficialDevice(Context context, BluetoothDevice device) {
        boolean isManufacturerOfficial =
                isBluetoothDeviceMetadataInList(
                        context,
                        device,
                        BluetoothDevice.METADATA_MANUFACTURER_NAME,
                        R.array.official_bt_device_manufacturer_names);
        boolean isModelOfficial =
                isBluetoothDeviceMetadataInList(
                        context,
                        device,
                        BluetoothDevice.METADATA_MODEL_NAME,
                        R.array.official_bt_device_model_names);
        return isManufacturerOfficial && isModelOfficial;
    }

    public static boolean isOfficialRemote(Context context, BluetoothDevice device) {
        return isRemote(context, device) && isOfficialDevice(context, device);
    }

    public static int getIcon(Context context, BluetoothDevice device) {
        if (device == null) {
            return 0;
        }
        final BluetoothClass bluetoothClass = device.getBluetoothClass();
        final int devClass = bluetoothClass.getDeviceClass();
        // Below ordering does matter
        if (isOfficialRemote(context, device)) {
            return R.drawable.ic_official_remote;
        } else if (isRemote(context, device)) {
            return R.drawable.ic_games;
        } else if (isBluetoothHeadset(device)) {
            return R.drawable.ic_headset;
        } else if ((devClass & MINOR_DEVICE_CLASS_POINTING) != 0) {
            return R.drawable.ic_mouse;
        } else if (isA2dpSource(device)) {
            return R.drawable.ic_baseline_smartphone_24dp;
        } else if ((devClass & MINOR_DEVICE_CLASS_REMOTE) != 0) {
            return R.drawable.ic_games;
        } else if ((devClass & MINOR_DEVICE_CLASS_JOYSTICK) != 0) {
            return R.drawable.ic_games;
        } else if ((devClass & MINOR_DEVICE_CLASS_GAMEPAD) != 0) {
            return R.drawable.ic_games;
        } else if ((devClass & MINOR_DEVICE_CLASS_KEYBOARD) != 0) {
            return R.drawable.ic_keyboard;
        }
        // Default for now
        return R.drawable.ic_bluetooth;
    }

    /**
     * @param context the context
     * @param device the bluetooth device
     * @param metadataKey one of BluetoothDevice.METADATA_*
     * @param stringArrayResId resource Id of <string-array> to match the metadata against
     * @return whether the specified metadata in within the list of stringArrayResId.
     */
    public static boolean isBluetoothDeviceMetadataInList(
            Context context, BluetoothDevice device, int metadataKey, int stringArrayResId) {
        if (context == null || device == null) {
            return false;
        }
        byte[] metadataBytes = device.getMetadata(metadataKey);
        if (metadataBytes == null) {
            return false;
        }
        final List<String> stringResList =
                Arrays.asList(context.getResources().getStringArray(stringArrayResId));
        if (stringResList == null || stringResList.isEmpty()) {
            return false;
        }
        for (String res : stringResList) {
            if (res.equals(new String(metadataBytes))) {
                return true;
            }
        }
        return false;
    }

    public static Class getBluetoothDeviceServiceClass(Context context) {
        String str = context.getString(R.string.bluetooth_device_service_class);
        try {
            return Class.forName(str);
        } catch (ClassNotFoundException e) {
            Log.e(TAG, "Class not found: " + str);
            return null;
        }
    }

    public static LocalBluetoothManager getLocalBluetoothManager(Context context) {
        final FutureTask<LocalBluetoothManager> localBluetoothManagerFutureTask =
                new FutureTask<>(
                        // Avoid StrictMode ThreadPolicy violation
                        () -> LocalBluetoothManager.getInstance(
                                context, (c, bluetoothManager) -> {}));
        try {
            localBluetoothManagerFutureTask.run();
            return localBluetoothManagerFutureTask.get();
        } catch (InterruptedException | ExecutionException e) {
            Log.w(TAG, "Error getting LocalBluetoothManager.", e);
            return null;
        }
    }

    public static CachedBluetoothDevice getCachedBluetoothDevice(
            Context context, BluetoothDevice device) {
        LocalBluetoothManager localBluetoothManager = getLocalBluetoothManager(context);
        if (localBluetoothManager != null) {
            return localBluetoothManager.getCachedDeviceManager().findDevice(device);
        }
        return null;
    }
}