summaryrefslogtreecommitdiff
path: root/Settings/src/com/android/tv/settings/accessories/BluetoothDevicesService.java
blob: abc3bb02710c2c2c8ae924a658308134280b4ddf (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
/*
 * Copyright (C) 2020 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 static com.android.tv.settings.accessories.ConnectedDevicesSliceUtils.GENERAL_SLICE_URI;

import android.app.Service;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHidHost;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.tv.settings.R;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/** The Service for handling Bluetooth-related logic. */
public class BluetoothDevicesService extends Service {

    private static final boolean DEBUG = false;
    private static final String TAG = "BtDevicesServices";

    private final List<BluetoothDeviceProvider.Listener> mListeners = new ArrayList<>();
    private final Binder mBinder = new LocalBinder();
    protected final Handler mHandler = new Handler(Looper.getMainLooper());

    /** Binder in BluetoothDeviceService. */
    public class LocalBinder extends Binder implements BluetoothDeviceProvider {

        public List<BluetoothDevice> getDevices() {
            return BluetoothDevicesService.this.getDevices();
        }

        @Override
        public void addListener(BluetoothDeviceProvider.Listener listener) {
            mHandler.post(() -> {
                mListeners.add(listener);

                // Trigger first update after listener callback is registered.
                for (BluetoothDevice device : getDevices()) {
                    if (device.isConnected()) {
                        listener.onDeviceUpdated(device);
                    }
                }
            });
        }

        @Override
        public void removeListener(BluetoothDeviceProvider.Listener listener) {
            mHandler.post(() -> mListeners.remove(listener));
        }

        @Override
        public void connectDevice(BluetoothDevice device) {
            BluetoothDevicesService.this.connectDevice(device);
        }

        @Override
        public void disconnectDevice(BluetoothDevice device) {
            BluetoothDevicesService.this.disconnectDevice(device);
        }

        @Override
        public void forgetDevice(BluetoothDevice device) {
            BluetoothDevicesService.this.forgetDevice(device);
        }

        @Override
        public void renameDevice(BluetoothDevice device, String newName) {
            BluetoothDevicesService.this.renameDevice(device, newName);
        }
    }

    BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            final BluetoothDevice device =
                    intent == null ? null : intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // The sequence of a typical connection is: acl connected, bonding, bonded, profile
            // connecting, profile connected.
            if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
                switch (state) {
                    case BluetoothDevice.BOND_BONDED:
                        break;
                    case BluetoothDevice.BOND_NONE:
                        mHandler.post(() -> onDeviceUpdated(device));
                        break;
                    case BluetoothDevice.BOND_BONDING:
                        break;
                    default:
                        if (DEBUG) {
                            Log.e(TAG, "unknown state " + state + " " + device);
                        }
                }
            } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                final int state =
                        intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
                // Actively refresh the connected devices slice.
                if (state == BluetoothAdapter.STATE_ON || state == BluetoothAdapter.STATE_OFF) {
                    getContentResolver().notifyChange(GENERAL_SLICE_URI, null);
                }
            } else {
                switch(action) {
                    case BluetoothHidHost.ACTION_CONNECTION_STATE_CHANGED:
                        if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                            mHandler.post(() -> onDeviceUpdated(device));
                        }
                        break;
                    case BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED:
                        int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1);
                        mHandler.post(() -> onA2dpConnectionStateChanged(device.getName(), state));
                        break;
                    case BluetoothDevice.ACTION_ACL_CONNECTED:
                        Log.i(TAG, "acl connected " + device);
                        if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                            mHandler.post(() -> onDeviceUpdated(device));
                        }
                        break;
                    case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                        Log.i(TAG, "acl disconnected " + device);
                        mHandler.post(() -> onDeviceUpdated(device));
                        break;
                    case BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED:
                        Log.i(TAG, "acl disconnect requested: " + device);
                        break;
                }
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (DEBUG) {
            Log.e(TAG, "onCreate");
        }
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        filter.addAction(BluetoothHidHost.ACTION_CONNECTION_STATE_CHANGED);
        filter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED); // Headset connection
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); // Bluetooth toggle
        registerReceiver(mBluetoothReceiver, filter);
    }

    @Override
    public void onDestroy() {
        if (DEBUG) {
            Log.e(TAG, "onDestroy");
        }
        unregisterReceiver(mBluetoothReceiver);
        mHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    @Override
    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
        for (BluetoothDevice device: getDevices()) {
            if (!device.isConnected()) {
                continue;
            }
            writer.printf("%s (%s):%n", device.getName(), device.getAddress());
        }
    }

    private void connectDevice(BluetoothDevice device) {
        if (device != null) {
            CachedBluetoothDevice cachedDevice =
                    AccessoryUtils.getCachedBluetoothDevice(this, device);
            if (cachedDevice != null) {
                cachedDevice.connect();
            }
        }
    }

    private void disconnectDevice(BluetoothDevice device) {
        if (device != null) {
            CachedBluetoothDevice cachedDevice =
                    AccessoryUtils.getCachedBluetoothDevice(this, device);
            if (cachedDevice != null) {
                cachedDevice.disconnect();
            }
        }
    }

    private static void forgetDevice(BluetoothDevice device) {
        if (device == null || !device.removeBond()) {
            Log.w(TAG, "failed to remove bond: " + device);
        }
    }

    private void renameDevice(BluetoothDevice device, String newName) {
        if (device != null) {
            device.setAlias(newName);
            mHandler.post(() -> onDeviceUpdated(device));
        }
    }

    private void onA2dpConnectionStateChanged(String deviceName, int connectionStatus) {
        String resStr;
        String text;
        switch (connectionStatus) {
            case BluetoothProfile.STATE_CONNECTED:
                resStr = getResources().getString(R.string.bluetooth_device_connected_toast);
                text = String.format(resStr, deviceName);
                Toast.makeText(BluetoothDevicesService.this.getApplicationContext(),
                        text, Toast.LENGTH_SHORT).show();
                break;
            case BluetoothProfile.STATE_DISCONNECTED:
                resStr = getResources().getString(R.string.bluetooth_device_disconnected_toast);
                text = String.format(resStr, deviceName);
                Toast.makeText(BluetoothDevicesService.this.getApplicationContext(),
                        text, Toast.LENGTH_SHORT).show();
                break;
            case BluetoothProfile.STATE_CONNECTING:
            case BluetoothProfile.STATE_DISCONNECTING:
            default:
                break;
        }
    }

    private void onDeviceUpdated(BluetoothDevice device) {
        mListeners.forEach(listener -> listener.onDeviceUpdated(device));
    }

    /** Returns the BluetoothDevice object with the input address. */
    public static BluetoothDevice findDevice(String address) {
        List<BluetoothDevice> devices = getDevices();
        BluetoothDevice curDevice = null;
        for (BluetoothDevice device: devices) {
            if (address.equals(device.getAddress())) {
                curDevice = device;
                break;
            }
        }
        return curDevice;
    }

    private static List<BluetoothDevice> getDevices() {
        final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        if (btAdapter != null) {
            return new ArrayList<>(btAdapter.getBondedDevices());
        }
        return new ArrayList<>(); // Empty list
    }
}