blob: 9c01dacd7ca527a8165ceec96aa074752d5a32e9 [file] [log] [blame]
Jason Monk7ce96b92015-02-02 11:27:58 -05001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.settingslib.bluetooth;
18
19import android.bluetooth.BluetoothClass;
20import android.bluetooth.BluetoothDevice;
21import android.bluetooth.BluetoothProfile;
22import android.bluetooth.BluetoothUuid;
23import android.content.Context;
24import android.content.SharedPreferences;
25import android.os.ParcelUuid;
26import android.os.SystemClock;
27import android.text.TextUtils;
28import android.util.Log;
29import android.bluetooth.BluetoothAdapter;
30
Jason Monkbe3c5db2015-02-04 13:00:55 -050031import com.android.settingslib.R;
32
Jason Monk7ce96b92015-02-02 11:27:58 -050033import java.util.ArrayList;
34import java.util.Collection;
35import java.util.Collections;
36import java.util.HashMap;
37import java.util.List;
38
39/**
40 * CachedBluetoothDevice represents a remote Bluetooth device. It contains
41 * attributes of the device (such as the address, name, RSSI, etc.) and
42 * functionality that can be performed on the device (connect, pair, disconnect,
43 * etc.).
44 */
Fan Zhang82dd3b02016-12-27 13:13:00 -080045public class CachedBluetoothDevice implements Comparable<CachedBluetoothDevice> {
Jason Monk7ce96b92015-02-02 11:27:58 -050046 private static final String TAG = "CachedBluetoothDevice";
47 private static final boolean DEBUG = Utils.V;
48
49 private final Context mContext;
50 private final LocalBluetoothAdapter mLocalAdapter;
51 private final LocalBluetoothProfileManager mProfileManager;
52 private final BluetoothDevice mDevice;
53 private String mName;
54 private short mRssi;
55 private BluetoothClass mBtClass;
56 private HashMap<LocalBluetoothProfile, Integer> mProfileConnectionState;
57
58 private final List<LocalBluetoothProfile> mProfiles =
59 new ArrayList<LocalBluetoothProfile>();
60
61 // List of profiles that were previously in mProfiles, but have been removed
62 private final List<LocalBluetoothProfile> mRemovedProfiles =
63 new ArrayList<LocalBluetoothProfile>();
64
65 // Device supports PANU but not NAP: remove PanProfile after device disconnects from NAP
66 private boolean mLocalNapRoleConnected;
67
68 private boolean mVisible;
69
Jason Monk7ce96b92015-02-02 11:27:58 -050070 private int mMessageRejectionCount;
71
72 private final Collection<Callback> mCallbacks = new ArrayList<Callback>();
73
74 // Following constants indicate the user's choices of Phone book/message access settings
75 // User hasn't made any choice or settings app has wiped out the memory
76 public final static int ACCESS_UNKNOWN = 0;
77 // User has accepted the connection and let Settings app remember the decision
78 public final static int ACCESS_ALLOWED = 1;
79 // User has rejected the connection and let Settings app remember the decision
80 public final static int ACCESS_REJECTED = 2;
81
82 // How many times user should reject the connection to make the choice persist.
83 private final static int MESSAGE_REJECTION_COUNT_LIMIT_TO_PERSIST = 2;
84
85 private final static String MESSAGE_REJECTION_COUNT_PREFS_NAME = "bluetooth_message_reject";
86
87 /**
88 * When we connect to multiple profiles, we only want to display a single
89 * error even if they all fail. This tracks that state.
90 */
91 private boolean mIsConnectingErrorPossible;
92
93 /**
94 * Last time a bt profile auto-connect was attempted.
95 * If an ACTION_UUID intent comes in within
96 * MAX_UUID_DELAY_FOR_AUTO_CONNECT milliseconds, we will try auto-connect
97 * again with the new UUIDs
98 */
99 private long mConnectAttempted;
100
101 // See mConnectAttempted
102 private static final long MAX_UUID_DELAY_FOR_AUTO_CONNECT = 5000;
Etan Cohen50d47612015-03-31 12:45:23 -0700103 private static final long MAX_HOGP_DELAY_FOR_AUTO_CONNECT = 30000;
Jason Monk7ce96b92015-02-02 11:27:58 -0500104
Jason Monk7ce96b92015-02-02 11:27:58 -0500105 /**
106 * Describes the current device and profile for logging.
107 *
108 * @param profile Profile to describe
109 * @return Description of the device and profile
110 */
111 private String describe(LocalBluetoothProfile profile) {
112 StringBuilder sb = new StringBuilder();
113 sb.append("Address:").append(mDevice);
114 if (profile != null) {
115 sb.append(" Profile:").append(profile);
116 }
117
118 return sb.toString();
119 }
120
121 void onProfileStateChanged(LocalBluetoothProfile profile, int newProfileState) {
122 if (Utils.D) {
123 Log.d(TAG, "onProfileStateChanged: profile " + profile +
124 " newProfileState " + newProfileState);
125 }
126 if (mLocalAdapter.getBluetoothState() == BluetoothAdapter.STATE_TURNING_OFF)
127 {
128 if (Utils.D) Log.d(TAG, " BT Turninig Off...Profile conn state change ignored...");
129 return;
130 }
131 mProfileConnectionState.put(profile, newProfileState);
132 if (newProfileState == BluetoothProfile.STATE_CONNECTED) {
133 if (profile instanceof MapProfile) {
134 profile.setPreferred(mDevice, true);
135 } else if (!mProfiles.contains(profile)) {
136 mRemovedProfiles.remove(profile);
137 mProfiles.add(profile);
138 if (profile instanceof PanProfile &&
139 ((PanProfile) profile).isLocalRoleNap(mDevice)) {
140 // Device doesn't support NAP, so remove PanProfile on disconnect
141 mLocalNapRoleConnected = true;
142 }
143 }
144 } else if (profile instanceof MapProfile &&
145 newProfileState == BluetoothProfile.STATE_DISCONNECTED) {
146 profile.setPreferred(mDevice, false);
147 } else if (mLocalNapRoleConnected && profile instanceof PanProfile &&
148 ((PanProfile) profile).isLocalRoleNap(mDevice) &&
149 newProfileState == BluetoothProfile.STATE_DISCONNECTED) {
150 Log.d(TAG, "Removing PanProfile from device after NAP disconnect");
151 mProfiles.remove(profile);
152 mRemovedProfiles.add(profile);
153 mLocalNapRoleConnected = false;
154 }
155 }
156
157 CachedBluetoothDevice(Context context,
158 LocalBluetoothAdapter adapter,
159 LocalBluetoothProfileManager profileManager,
160 BluetoothDevice device) {
161 mContext = context;
162 mLocalAdapter = adapter;
163 mProfileManager = profileManager;
164 mDevice = device;
165 mProfileConnectionState = new HashMap<LocalBluetoothProfile, Integer>();
166 fillData();
167 }
168
169 public void disconnect() {
170 for (LocalBluetoothProfile profile : mProfiles) {
171 disconnect(profile);
172 }
173 // Disconnect PBAP server in case its connected
174 // This is to ensure all the profiles are disconnected as some CK/Hs do not
175 // disconnect PBAP connection when HF connection is brought down
176 PbapServerProfile PbapProfile = mProfileManager.getPbapProfile();
177 if (PbapProfile.getConnectionStatus(mDevice) == BluetoothProfile.STATE_CONNECTED)
178 {
179 PbapProfile.disconnect(mDevice);
180 }
181 }
182
183 public void disconnect(LocalBluetoothProfile profile) {
184 if (profile.disconnect(mDevice)) {
185 if (Utils.D) {
186 Log.d(TAG, "Command sent successfully:DISCONNECT " + describe(profile));
187 }
188 }
189 }
190
191 public void connect(boolean connectAllProfiles) {
192 if (!ensurePaired()) {
193 return;
194 }
195
196 mConnectAttempted = SystemClock.elapsedRealtime();
197 connectWithoutResettingTimer(connectAllProfiles);
198 }
199
200 void onBondingDockConnect() {
201 // Attempt to connect if UUIDs are available. Otherwise,
202 // we will connect when the ACTION_UUID intent arrives.
203 connect(false);
204 }
205
206 private void connectWithoutResettingTimer(boolean connectAllProfiles) {
207 // Try to initialize the profiles if they were not.
208 if (mProfiles.isEmpty()) {
209 // if mProfiles is empty, then do not invoke updateProfiles. This causes a race
210 // condition with carkits during pairing, wherein RemoteDevice.UUIDs have been updated
211 // from bluetooth stack but ACTION.uuid is not sent yet.
212 // Eventually ACTION.uuid will be received which shall trigger the connection of the
213 // various profiles
214 // If UUIDs are not available yet, connect will be happen
215 // upon arrival of the ACTION_UUID intent.
216 Log.d(TAG, "No profiles. Maybe we will connect later");
217 return;
218 }
219
220 // Reset the only-show-one-error-dialog tracking variable
221 mIsConnectingErrorPossible = true;
222
223 int preferredProfiles = 0;
224 for (LocalBluetoothProfile profile : mProfiles) {
225 if (connectAllProfiles ? profile.isConnectable() : profile.isAutoConnectable()) {
226 if (profile.isPreferred(mDevice)) {
227 ++preferredProfiles;
228 connectInt(profile);
229 }
230 }
231 }
232 if (DEBUG) Log.d(TAG, "Preferred profiles = " + preferredProfiles);
233
234 if (preferredProfiles == 0) {
235 connectAutoConnectableProfiles();
236 }
237 }
238
239 private void connectAutoConnectableProfiles() {
240 if (!ensurePaired()) {
241 return;
242 }
243 // Reset the only-show-one-error-dialog tracking variable
244 mIsConnectingErrorPossible = true;
245
246 for (LocalBluetoothProfile profile : mProfiles) {
247 if (profile.isAutoConnectable()) {
248 profile.setPreferred(mDevice, true);
249 connectInt(profile);
250 }
251 }
252 }
253
254 /**
255 * Connect this device to the specified profile.
256 *
257 * @param profile the profile to use with the remote device
258 */
259 public void connectProfile(LocalBluetoothProfile profile) {
260 mConnectAttempted = SystemClock.elapsedRealtime();
261 // Reset the only-show-one-error-dialog tracking variable
262 mIsConnectingErrorPossible = true;
263 connectInt(profile);
264 // Refresh the UI based on profile.connect() call
265 refresh();
266 }
267
268 synchronized void connectInt(LocalBluetoothProfile profile) {
269 if (!ensurePaired()) {
270 return;
271 }
272 if (profile.connect(mDevice)) {
273 if (Utils.D) {
274 Log.d(TAG, "Command sent successfully:CONNECT " + describe(profile));
275 }
276 return;
277 }
278 Log.i(TAG, "Failed to connect " + profile.toString() + " to " + mName);
279 }
280
281 private boolean ensurePaired() {
282 if (getBondState() == BluetoothDevice.BOND_NONE) {
283 startPairing();
284 return false;
285 } else {
286 return true;
287 }
288 }
289
290 public boolean startPairing() {
291 // Pairing is unreliable while scanning, so cancel discovery
292 if (mLocalAdapter.isDiscovering()) {
293 mLocalAdapter.cancelDiscovery();
294 }
295
296 if (!mDevice.createBond()) {
297 return false;
298 }
299
Jason Monk7ce96b92015-02-02 11:27:58 -0500300 return true;
301 }
302
303 /**
304 * Return true if user initiated pairing on this device. The message text is
305 * slightly different for local vs. remote initiated pairing dialogs.
306 */
307 boolean isUserInitiatedPairing() {
Jakub Pawlowski0278ab92016-07-20 11:55:48 -0700308 return mDevice.isBondingInitiatedLocally();
Jason Monk7ce96b92015-02-02 11:27:58 -0500309 }
310
311 public void unpair() {
312 int state = getBondState();
313
314 if (state == BluetoothDevice.BOND_BONDING) {
315 mDevice.cancelBondProcess();
316 }
317
318 if (state != BluetoothDevice.BOND_NONE) {
319 final BluetoothDevice dev = mDevice;
320 if (dev != null) {
321 final boolean successful = dev.removeBond();
322 if (successful) {
323 if (Utils.D) {
324 Log.d(TAG, "Command sent successfully:REMOVE_BOND " + describe(null));
325 }
326 } else if (Utils.V) {
327 Log.v(TAG, "Framework rejected command immediately:REMOVE_BOND " +
328 describe(null));
329 }
330 }
331 }
332 }
333
334 public int getProfileConnectionState(LocalBluetoothProfile profile) {
335 if (mProfileConnectionState == null ||
336 mProfileConnectionState.get(profile) == null) {
337 // If cache is empty make the binder call to get the state
338 int state = profile.getConnectionStatus(mDevice);
339 mProfileConnectionState.put(profile, state);
340 }
341 return mProfileConnectionState.get(profile);
342 }
343
344 public void clearProfileConnectionState ()
345 {
346 if (Utils.D) {
347 Log.d(TAG," Clearing all connection state for dev:" + mDevice.getName());
348 }
349 for (LocalBluetoothProfile profile :getProfiles()) {
350 mProfileConnectionState.put(profile, BluetoothProfile.STATE_DISCONNECTED);
351 }
352 }
353
354 // TODO: do any of these need to run async on a background thread?
355 private void fillData() {
356 fetchName();
357 fetchBtClass();
358 updateProfiles();
359 migratePhonebookPermissionChoice();
360 migrateMessagePermissionChoice();
361 fetchMessageRejectionCount();
362
363 mVisible = false;
364 dispatchAttributesChanged();
365 }
366
367 public BluetoothDevice getDevice() {
368 return mDevice;
369 }
370
Antony Sargent7ad051e2017-06-29 15:23:13 -0700371 /**
372 * Convenience method that can be mocked - it lets tests avoid having to call getDevice() which
373 * causes problems in tests since BluetoothDevice is final and cannot be mocked.
374 * @return the address of this device
375 */
376 public String getAddress() {
377 return mDevice.getAddress();
378 }
379
Jason Monk7ce96b92015-02-02 11:27:58 -0500380 public String getName() {
381 return mName;
382 }
383
384 /**
385 * Populate name from BluetoothDevice.ACTION_FOUND intent
386 */
387 void setNewName(String name) {
388 if (mName == null) {
389 mName = name;
390 if (mName == null || TextUtils.isEmpty(mName)) {
391 mName = mDevice.getAddress();
392 }
393 dispatchAttributesChanged();
394 }
395 }
396
397 /**
398 * user changes the device name
399 */
400 public void setName(String name) {
401 if (!mName.equals(name)) {
402 mName = name;
403 mDevice.setAlias(name);
404 dispatchAttributesChanged();
405 }
406 }
407
408 void refreshName() {
409 fetchName();
410 dispatchAttributesChanged();
411 }
412
413 private void fetchName() {
414 mName = mDevice.getAliasName();
415
416 if (TextUtils.isEmpty(mName)) {
417 mName = mDevice.getAddress();
418 if (DEBUG) Log.d(TAG, "Device has no name (yet), use address: " + mName);
419 }
420 }
421
422 void refresh() {
423 dispatchAttributesChanged();
424 }
425
426 public boolean isVisible() {
427 return mVisible;
428 }
429
430 public void setVisible(boolean visible) {
431 if (mVisible != visible) {
432 mVisible = visible;
433 dispatchAttributesChanged();
434 }
435 }
436
437 public int getBondState() {
438 return mDevice.getBondState();
439 }
440
441 void setRssi(short rssi) {
442 if (mRssi != rssi) {
443 mRssi = rssi;
444 dispatchAttributesChanged();
445 }
446 }
447
448 /**
449 * Checks whether we are connected to this device (any profile counts).
450 *
451 * @return Whether it is connected.
452 */
453 public boolean isConnected() {
454 for (LocalBluetoothProfile profile : mProfiles) {
455 int status = getProfileConnectionState(profile);
456 if (status == BluetoothProfile.STATE_CONNECTED) {
457 return true;
458 }
459 }
460
461 return false;
462 }
463
464 public boolean isConnectedProfile(LocalBluetoothProfile profile) {
465 int status = getProfileConnectionState(profile);
466 return status == BluetoothProfile.STATE_CONNECTED;
467
468 }
469
470 public boolean isBusy() {
471 for (LocalBluetoothProfile profile : mProfiles) {
472 int status = getProfileConnectionState(profile);
473 if (status == BluetoothProfile.STATE_CONNECTING
474 || status == BluetoothProfile.STATE_DISCONNECTING) {
475 return true;
476 }
477 }
478 return getBondState() == BluetoothDevice.BOND_BONDING;
479 }
480
481 /**
482 * Fetches a new value for the cached BT class.
483 */
484 private void fetchBtClass() {
485 mBtClass = mDevice.getBluetoothClass();
486 }
487
488 private boolean updateProfiles() {
489 ParcelUuid[] uuids = mDevice.getUuids();
490 if (uuids == null) return false;
491
492 ParcelUuid[] localUuids = mLocalAdapter.getUuids();
493 if (localUuids == null) return false;
494
495 /**
496 * Now we know if the device supports PBAP, update permissions...
497 */
498 processPhonebookAccess();
499
500 mProfileManager.updateProfiles(uuids, localUuids, mProfiles, mRemovedProfiles,
501 mLocalNapRoleConnected, mDevice);
502
503 if (DEBUG) {
504 Log.e(TAG, "updating profiles for " + mDevice.getAliasName());
505 BluetoothClass bluetoothClass = mDevice.getBluetoothClass();
506
507 if (bluetoothClass != null) Log.v(TAG, "Class: " + bluetoothClass.toString());
508 Log.v(TAG, "UUID:");
509 for (ParcelUuid uuid : uuids) {
510 Log.v(TAG, " " + uuid);
511 }
512 }
513 return true;
514 }
515
516 /**
517 * Refreshes the UI for the BT class, including fetching the latest value
518 * for the class.
519 */
520 void refreshBtClass() {
521 fetchBtClass();
522 dispatchAttributesChanged();
523 }
524
525 /**
526 * Refreshes the UI when framework alerts us of a UUID change.
527 */
528 void onUuidChanged() {
529 updateProfiles();
Etan Cohen50d47612015-03-31 12:45:23 -0700530 ParcelUuid[] uuids = mDevice.getUuids();
Venkat Raghavan05e08c32015-04-06 16:26:11 -0700531
Etan Cohen50d47612015-03-31 12:45:23 -0700532 long timeout = MAX_UUID_DELAY_FOR_AUTO_CONNECT;
Venkat Raghavan05e08c32015-04-06 16:26:11 -0700533 if (BluetoothUuid.isUuidPresent(uuids, BluetoothUuid.Hogp)) {
534 timeout = MAX_HOGP_DELAY_FOR_AUTO_CONNECT;
535 }
Jason Monk7ce96b92015-02-02 11:27:58 -0500536
537 if (DEBUG) {
Etan Cohen50d47612015-03-31 12:45:23 -0700538 Log.d(TAG, "onUuidChanged: Time since last connect"
Jason Monk7ce96b92015-02-02 11:27:58 -0500539 + (SystemClock.elapsedRealtime() - mConnectAttempted));
540 }
541
542 /*
Venkat Raghavan05e08c32015-04-06 16:26:11 -0700543 * If a connect was attempted earlier without any UUID, we will do the connect now.
544 * Otherwise, allow the connect on UUID change.
Jason Monk7ce96b92015-02-02 11:27:58 -0500545 */
546 if (!mProfiles.isEmpty()
Andre Eisenbach7be83c52015-09-03 15:20:09 -0700547 && ((mConnectAttempted + timeout) > SystemClock.elapsedRealtime())) {
Jason Monk7ce96b92015-02-02 11:27:58 -0500548 connectWithoutResettingTimer(false);
549 }
Andre Eisenbach7be83c52015-09-03 15:20:09 -0700550
Jason Monk7ce96b92015-02-02 11:27:58 -0500551 dispatchAttributesChanged();
552 }
553
554 void onBondingStateChanged(int bondState) {
555 if (bondState == BluetoothDevice.BOND_NONE) {
556 mProfiles.clear();
Jason Monk7ce96b92015-02-02 11:27:58 -0500557 setPhonebookPermissionChoice(ACCESS_UNKNOWN);
558 setMessagePermissionChoice(ACCESS_UNKNOWN);
Casper Bonde424681e2015-05-04 22:07:45 -0700559 setSimPermissionChoice(ACCESS_UNKNOWN);
Jason Monk7ce96b92015-02-02 11:27:58 -0500560 mMessageRejectionCount = 0;
561 saveMessageRejectionCount();
562 }
563
564 refresh();
565
566 if (bondState == BluetoothDevice.BOND_BONDED) {
567 if (mDevice.isBluetoothDock()) {
568 onBondingDockConnect();
Jakub Pawlowski0278ab92016-07-20 11:55:48 -0700569 } else if (mDevice.isBondingInitiatedLocally()) {
Jason Monk7ce96b92015-02-02 11:27:58 -0500570 connect(false);
571 }
Jason Monk7ce96b92015-02-02 11:27:58 -0500572 }
573 }
574
575 void setBtClass(BluetoothClass btClass) {
576 if (btClass != null && mBtClass != btClass) {
577 mBtClass = btClass;
578 dispatchAttributesChanged();
579 }
580 }
581
582 public BluetoothClass getBtClass() {
583 return mBtClass;
584 }
585
586 public List<LocalBluetoothProfile> getProfiles() {
587 return Collections.unmodifiableList(mProfiles);
588 }
589
590 public List<LocalBluetoothProfile> getConnectableProfiles() {
591 List<LocalBluetoothProfile> connectableProfiles =
592 new ArrayList<LocalBluetoothProfile>();
593 for (LocalBluetoothProfile profile : mProfiles) {
594 if (profile.isConnectable()) {
595 connectableProfiles.add(profile);
596 }
597 }
598 return connectableProfiles;
599 }
600
601 public List<LocalBluetoothProfile> getRemovedProfiles() {
602 return mRemovedProfiles;
603 }
604
605 public void registerCallback(Callback callback) {
606 synchronized (mCallbacks) {
607 mCallbacks.add(callback);
608 }
609 }
610
611 public void unregisterCallback(Callback callback) {
612 synchronized (mCallbacks) {
613 mCallbacks.remove(callback);
614 }
615 }
616
617 private void dispatchAttributesChanged() {
618 synchronized (mCallbacks) {
619 for (Callback callback : mCallbacks) {
620 callback.onDeviceAttributesChanged();
621 }
622 }
623 }
624
625 @Override
626 public String toString() {
627 return mDevice.toString();
628 }
629
630 @Override
631 public boolean equals(Object o) {
632 if ((o == null) || !(o instanceof CachedBluetoothDevice)) {
633 return false;
634 }
635 return mDevice.equals(((CachedBluetoothDevice) o).mDevice);
636 }
637
638 @Override
639 public int hashCode() {
640 return mDevice.getAddress().hashCode();
641 }
642
643 // This comparison uses non-final fields so the sort order may change
644 // when device attributes change (such as bonding state). Settings
645 // will completely refresh the device list when this happens.
646 public int compareTo(CachedBluetoothDevice another) {
647 // Connected above not connected
648 int comparison = (another.isConnected() ? 1 : 0) - (isConnected() ? 1 : 0);
649 if (comparison != 0) return comparison;
650
651 // Paired above not paired
652 comparison = (another.getBondState() == BluetoothDevice.BOND_BONDED ? 1 : 0) -
653 (getBondState() == BluetoothDevice.BOND_BONDED ? 1 : 0);
654 if (comparison != 0) return comparison;
655
656 // Visible above not visible
657 comparison = (another.mVisible ? 1 : 0) - (mVisible ? 1 : 0);
658 if (comparison != 0) return comparison;
659
660 // Stronger signal above weaker signal
661 comparison = another.mRssi - mRssi;
662 if (comparison != 0) return comparison;
663
664 // Fallback on name
665 return mName.compareTo(another.mName);
666 }
667
668 public interface Callback {
669 void onDeviceAttributesChanged();
670 }
671
672 public int getPhonebookPermissionChoice() {
673 int permission = mDevice.getPhonebookAccessPermission();
674 if (permission == BluetoothDevice.ACCESS_ALLOWED) {
675 return ACCESS_ALLOWED;
676 } else if (permission == BluetoothDevice.ACCESS_REJECTED) {
677 return ACCESS_REJECTED;
678 }
679 return ACCESS_UNKNOWN;
680 }
681
682 public void setPhonebookPermissionChoice(int permissionChoice) {
683 int permission = BluetoothDevice.ACCESS_UNKNOWN;
684 if (permissionChoice == ACCESS_ALLOWED) {
685 permission = BluetoothDevice.ACCESS_ALLOWED;
686 } else if (permissionChoice == ACCESS_REJECTED) {
687 permission = BluetoothDevice.ACCESS_REJECTED;
688 }
689 mDevice.setPhonebookAccessPermission(permission);
690 }
691
692 // Migrates data from old data store (in Settings app's shared preferences) to new (in Bluetooth
693 // app's shared preferences).
694 private void migratePhonebookPermissionChoice() {
695 SharedPreferences preferences = mContext.getSharedPreferences(
696 "bluetooth_phonebook_permission", Context.MODE_PRIVATE);
697 if (!preferences.contains(mDevice.getAddress())) {
698 return;
699 }
700
701 if (mDevice.getPhonebookAccessPermission() == BluetoothDevice.ACCESS_UNKNOWN) {
702 int oldPermission = preferences.getInt(mDevice.getAddress(), ACCESS_UNKNOWN);
703 if (oldPermission == ACCESS_ALLOWED) {
704 mDevice.setPhonebookAccessPermission(BluetoothDevice.ACCESS_ALLOWED);
705 } else if (oldPermission == ACCESS_REJECTED) {
706 mDevice.setPhonebookAccessPermission(BluetoothDevice.ACCESS_REJECTED);
707 }
708 }
709
710 SharedPreferences.Editor editor = preferences.edit();
711 editor.remove(mDevice.getAddress());
712 editor.commit();
713 }
714
715 public int getMessagePermissionChoice() {
716 int permission = mDevice.getMessageAccessPermission();
717 if (permission == BluetoothDevice.ACCESS_ALLOWED) {
718 return ACCESS_ALLOWED;
719 } else if (permission == BluetoothDevice.ACCESS_REJECTED) {
720 return ACCESS_REJECTED;
721 }
722 return ACCESS_UNKNOWN;
723 }
724
725 public void setMessagePermissionChoice(int permissionChoice) {
726 int permission = BluetoothDevice.ACCESS_UNKNOWN;
727 if (permissionChoice == ACCESS_ALLOWED) {
728 permission = BluetoothDevice.ACCESS_ALLOWED;
729 } else if (permissionChoice == ACCESS_REJECTED) {
730 permission = BluetoothDevice.ACCESS_REJECTED;
731 }
732 mDevice.setMessageAccessPermission(permission);
733 }
734
Casper Bonde424681e2015-05-04 22:07:45 -0700735 public int getSimPermissionChoice() {
736 int permission = mDevice.getSimAccessPermission();
737 if (permission == BluetoothDevice.ACCESS_ALLOWED) {
738 return ACCESS_ALLOWED;
739 } else if (permission == BluetoothDevice.ACCESS_REJECTED) {
740 return ACCESS_REJECTED;
741 }
742 return ACCESS_UNKNOWN;
743 }
744
745 void setSimPermissionChoice(int permissionChoice) {
746 int permission = BluetoothDevice.ACCESS_UNKNOWN;
747 if (permissionChoice == ACCESS_ALLOWED) {
748 permission = BluetoothDevice.ACCESS_ALLOWED;
749 } else if (permissionChoice == ACCESS_REJECTED) {
750 permission = BluetoothDevice.ACCESS_REJECTED;
751 }
752 mDevice.setSimAccessPermission(permission);
753 }
754
Jason Monk7ce96b92015-02-02 11:27:58 -0500755 // Migrates data from old data store (in Settings app's shared preferences) to new (in Bluetooth
756 // app's shared preferences).
757 private void migrateMessagePermissionChoice() {
758 SharedPreferences preferences = mContext.getSharedPreferences(
759 "bluetooth_message_permission", Context.MODE_PRIVATE);
760 if (!preferences.contains(mDevice.getAddress())) {
761 return;
762 }
763
764 if (mDevice.getMessageAccessPermission() == BluetoothDevice.ACCESS_UNKNOWN) {
765 int oldPermission = preferences.getInt(mDevice.getAddress(), ACCESS_UNKNOWN);
766 if (oldPermission == ACCESS_ALLOWED) {
767 mDevice.setMessageAccessPermission(BluetoothDevice.ACCESS_ALLOWED);
768 } else if (oldPermission == ACCESS_REJECTED) {
769 mDevice.setMessageAccessPermission(BluetoothDevice.ACCESS_REJECTED);
770 }
771 }
772
773 SharedPreferences.Editor editor = preferences.edit();
774 editor.remove(mDevice.getAddress());
775 editor.commit();
776 }
777
778 /**
779 * @return Whether this rejection should persist.
780 */
781 public boolean checkAndIncreaseMessageRejectionCount() {
782 if (mMessageRejectionCount < MESSAGE_REJECTION_COUNT_LIMIT_TO_PERSIST) {
783 mMessageRejectionCount++;
784 saveMessageRejectionCount();
785 }
786 return mMessageRejectionCount >= MESSAGE_REJECTION_COUNT_LIMIT_TO_PERSIST;
787 }
788
789 private void fetchMessageRejectionCount() {
790 SharedPreferences preference = mContext.getSharedPreferences(
791 MESSAGE_REJECTION_COUNT_PREFS_NAME, Context.MODE_PRIVATE);
792 mMessageRejectionCount = preference.getInt(mDevice.getAddress(), 0);
793 }
794
795 private void saveMessageRejectionCount() {
796 SharedPreferences.Editor editor = mContext.getSharedPreferences(
797 MESSAGE_REJECTION_COUNT_PREFS_NAME, Context.MODE_PRIVATE).edit();
798 if (mMessageRejectionCount == 0) {
799 editor.remove(mDevice.getAddress());
800 } else {
801 editor.putInt(mDevice.getAddress(), mMessageRejectionCount);
802 }
803 editor.commit();
804 }
805
806 private void processPhonebookAccess() {
807 if (mDevice.getBondState() != BluetoothDevice.BOND_BONDED) return;
808
809 ParcelUuid[] uuids = mDevice.getUuids();
810 if (BluetoothUuid.containsAnyUuid(uuids, PbapServerProfile.PBAB_CLIENT_UUIDS)) {
811 // The pairing dialog now warns of phone-book access for paired devices.
812 // No separate prompt is displayed after pairing.
Sanket Padawe78c23762015-06-01 15:55:30 -0700813 if (getPhonebookPermissionChoice() == CachedBluetoothDevice.ACCESS_UNKNOWN) {
Sanket Padawe07533db2015-11-11 15:01:35 -0800814 if (mDevice.getBluetoothClass().getDeviceClass()
Hemant Guptab8d267a2016-06-07 12:53:59 +0530815 == BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE ||
816 mDevice.getBluetoothClass().getDeviceClass()
817 == BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET) {
Sanket Padawe07533db2015-11-11 15:01:35 -0800818 setPhonebookPermissionChoice(CachedBluetoothDevice.ACCESS_ALLOWED);
819 } else {
820 setPhonebookPermissionChoice(CachedBluetoothDevice.ACCESS_REJECTED);
821 }
Sanket Padawe78c23762015-06-01 15:55:30 -0700822 }
Jason Monk7ce96b92015-02-02 11:27:58 -0500823 }
824 }
Jason Monkbe3c5db2015-02-04 13:00:55 -0500825
826 public int getMaxConnectionState() {
827 int maxState = BluetoothProfile.STATE_DISCONNECTED;
828 for (LocalBluetoothProfile profile : getProfiles()) {
829 int connectionStatus = getProfileConnectionState(profile);
830 if (connectionStatus > maxState) {
831 maxState = connectionStatus;
832 }
833 }
834 return maxState;
835 }
836
837 /**
838 * @return resource for string that discribes the connection state of this device.
839 */
840 public int getConnectionSummary() {
841 boolean profileConnected = false; // at least one profile is connected
842 boolean a2dpNotConnected = false; // A2DP is preferred but not connected
Sanket Agarwalf8a1c912016-01-26 20:12:52 -0800843 boolean hfpNotConnected = false; // HFP is preferred but not connected
Jason Monkbe3c5db2015-02-04 13:00:55 -0500844
845 for (LocalBluetoothProfile profile : getProfiles()) {
846 int connectionStatus = getProfileConnectionState(profile);
847
848 switch (connectionStatus) {
849 case BluetoothProfile.STATE_CONNECTING:
850 case BluetoothProfile.STATE_DISCONNECTING:
851 return Utils.getConnectionStateSummary(connectionStatus);
852
853 case BluetoothProfile.STATE_CONNECTED:
854 profileConnected = true;
855 break;
856
857 case BluetoothProfile.STATE_DISCONNECTED:
858 if (profile.isProfileReady()) {
Sanket Agarwalf8a1c912016-01-26 20:12:52 -0800859 if ((profile instanceof A2dpProfile) ||
Sanket Agarwal1bec6a52015-10-21 18:23:27 -0700860 (profile instanceof A2dpSinkProfile)){
Jason Monkbe3c5db2015-02-04 13:00:55 -0500861 a2dpNotConnected = true;
Sanket Agarwalf8a1c912016-01-26 20:12:52 -0800862 } else if ((profile instanceof HeadsetProfile) ||
863 (profile instanceof HfpClientProfile)) {
864 hfpNotConnected = true;
Jason Monkbe3c5db2015-02-04 13:00:55 -0500865 }
866 }
867 break;
868 }
869 }
870
871 if (profileConnected) {
Sanket Agarwalf8a1c912016-01-26 20:12:52 -0800872 if (a2dpNotConnected && hfpNotConnected) {
Jason Monkbe3c5db2015-02-04 13:00:55 -0500873 return R.string.bluetooth_connected_no_headset_no_a2dp;
874 } else if (a2dpNotConnected) {
875 return R.string.bluetooth_connected_no_a2dp;
Sanket Agarwalf8a1c912016-01-26 20:12:52 -0800876 } else if (hfpNotConnected) {
Jason Monkbe3c5db2015-02-04 13:00:55 -0500877 return R.string.bluetooth_connected_no_headset;
878 } else {
879 return R.string.bluetooth_connected;
880 }
881 }
882
883 return getBondState() == BluetoothDevice.BOND_BONDING ? R.string.bluetooth_pairing : 0;
884 }
Jason Monk7ce96b92015-02-02 11:27:58 -0500885}