blob: 5f302c6a50359553d66cece64a128e2a74dfa73f [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) {
xutianguo22bbb8192016-06-22 11:32:00 +0800335 if (mProfileConnectionState.get(profile) == null) {
Jason Monk7ce96b92015-02-02 11:27:58 -0500336 // If cache is empty make the binder call to get the state
337 int state = profile.getConnectionStatus(mDevice);
338 mProfileConnectionState.put(profile, state);
339 }
340 return mProfileConnectionState.get(profile);
341 }
342
343 public void clearProfileConnectionState ()
344 {
345 if (Utils.D) {
346 Log.d(TAG," Clearing all connection state for dev:" + mDevice.getName());
347 }
348 for (LocalBluetoothProfile profile :getProfiles()) {
349 mProfileConnectionState.put(profile, BluetoothProfile.STATE_DISCONNECTED);
350 }
351 }
352
353 // TODO: do any of these need to run async on a background thread?
354 private void fillData() {
355 fetchName();
356 fetchBtClass();
357 updateProfiles();
358 migratePhonebookPermissionChoice();
359 migrateMessagePermissionChoice();
360 fetchMessageRejectionCount();
361
362 mVisible = false;
363 dispatchAttributesChanged();
364 }
365
366 public BluetoothDevice getDevice() {
367 return mDevice;
368 }
369
370 public String getName() {
371 return mName;
372 }
373
374 /**
375 * Populate name from BluetoothDevice.ACTION_FOUND intent
376 */
377 void setNewName(String name) {
378 if (mName == null) {
379 mName = name;
380 if (mName == null || TextUtils.isEmpty(mName)) {
381 mName = mDevice.getAddress();
382 }
383 dispatchAttributesChanged();
384 }
385 }
386
387 /**
388 * user changes the device name
389 */
390 public void setName(String name) {
391 if (!mName.equals(name)) {
392 mName = name;
393 mDevice.setAlias(name);
394 dispatchAttributesChanged();
395 }
396 }
397
398 void refreshName() {
399 fetchName();
400 dispatchAttributesChanged();
401 }
402
403 private void fetchName() {
404 mName = mDevice.getAliasName();
405
406 if (TextUtils.isEmpty(mName)) {
407 mName = mDevice.getAddress();
408 if (DEBUG) Log.d(TAG, "Device has no name (yet), use address: " + mName);
409 }
410 }
411
412 void refresh() {
413 dispatchAttributesChanged();
414 }
415
416 public boolean isVisible() {
417 return mVisible;
418 }
419
420 public void setVisible(boolean visible) {
421 if (mVisible != visible) {
422 mVisible = visible;
423 dispatchAttributesChanged();
424 }
425 }
426
427 public int getBondState() {
428 return mDevice.getBondState();
429 }
430
431 void setRssi(short rssi) {
432 if (mRssi != rssi) {
433 mRssi = rssi;
434 dispatchAttributesChanged();
435 }
436 }
437
438 /**
439 * Checks whether we are connected to this device (any profile counts).
440 *
441 * @return Whether it is connected.
442 */
443 public boolean isConnected() {
444 for (LocalBluetoothProfile profile : mProfiles) {
445 int status = getProfileConnectionState(profile);
446 if (status == BluetoothProfile.STATE_CONNECTED) {
447 return true;
448 }
449 }
450
451 return false;
452 }
453
454 public boolean isConnectedProfile(LocalBluetoothProfile profile) {
455 int status = getProfileConnectionState(profile);
456 return status == BluetoothProfile.STATE_CONNECTED;
457
458 }
459
460 public boolean isBusy() {
461 for (LocalBluetoothProfile profile : mProfiles) {
462 int status = getProfileConnectionState(profile);
463 if (status == BluetoothProfile.STATE_CONNECTING
464 || status == BluetoothProfile.STATE_DISCONNECTING) {
465 return true;
466 }
467 }
468 return getBondState() == BluetoothDevice.BOND_BONDING;
469 }
470
471 /**
472 * Fetches a new value for the cached BT class.
473 */
474 private void fetchBtClass() {
475 mBtClass = mDevice.getBluetoothClass();
476 }
477
478 private boolean updateProfiles() {
479 ParcelUuid[] uuids = mDevice.getUuids();
480 if (uuids == null) return false;
481
482 ParcelUuid[] localUuids = mLocalAdapter.getUuids();
483 if (localUuids == null) return false;
484
485 /**
486 * Now we know if the device supports PBAP, update permissions...
487 */
488 processPhonebookAccess();
489
490 mProfileManager.updateProfiles(uuids, localUuids, mProfiles, mRemovedProfiles,
491 mLocalNapRoleConnected, mDevice);
492
493 if (DEBUG) {
494 Log.e(TAG, "updating profiles for " + mDevice.getAliasName());
495 BluetoothClass bluetoothClass = mDevice.getBluetoothClass();
496
497 if (bluetoothClass != null) Log.v(TAG, "Class: " + bluetoothClass.toString());
498 Log.v(TAG, "UUID:");
499 for (ParcelUuid uuid : uuids) {
500 Log.v(TAG, " " + uuid);
501 }
502 }
503 return true;
504 }
505
506 /**
507 * Refreshes the UI for the BT class, including fetching the latest value
508 * for the class.
509 */
510 void refreshBtClass() {
511 fetchBtClass();
512 dispatchAttributesChanged();
513 }
514
515 /**
516 * Refreshes the UI when framework alerts us of a UUID change.
517 */
518 void onUuidChanged() {
519 updateProfiles();
Etan Cohen50d47612015-03-31 12:45:23 -0700520 ParcelUuid[] uuids = mDevice.getUuids();
Venkat Raghavan05e08c32015-04-06 16:26:11 -0700521
Etan Cohen50d47612015-03-31 12:45:23 -0700522 long timeout = MAX_UUID_DELAY_FOR_AUTO_CONNECT;
Venkat Raghavan05e08c32015-04-06 16:26:11 -0700523 if (BluetoothUuid.isUuidPresent(uuids, BluetoothUuid.Hogp)) {
524 timeout = MAX_HOGP_DELAY_FOR_AUTO_CONNECT;
525 }
Jason Monk7ce96b92015-02-02 11:27:58 -0500526
527 if (DEBUG) {
Etan Cohen50d47612015-03-31 12:45:23 -0700528 Log.d(TAG, "onUuidChanged: Time since last connect"
Jason Monk7ce96b92015-02-02 11:27:58 -0500529 + (SystemClock.elapsedRealtime() - mConnectAttempted));
530 }
531
532 /*
Venkat Raghavan05e08c32015-04-06 16:26:11 -0700533 * If a connect was attempted earlier without any UUID, we will do the connect now.
534 * Otherwise, allow the connect on UUID change.
Jason Monk7ce96b92015-02-02 11:27:58 -0500535 */
536 if (!mProfiles.isEmpty()
Andre Eisenbach7be83c52015-09-03 15:20:09 -0700537 && ((mConnectAttempted + timeout) > SystemClock.elapsedRealtime())) {
Jason Monk7ce96b92015-02-02 11:27:58 -0500538 connectWithoutResettingTimer(false);
539 }
Andre Eisenbach7be83c52015-09-03 15:20:09 -0700540
Jason Monk7ce96b92015-02-02 11:27:58 -0500541 dispatchAttributesChanged();
542 }
543
544 void onBondingStateChanged(int bondState) {
545 if (bondState == BluetoothDevice.BOND_NONE) {
546 mProfiles.clear();
Jason Monk7ce96b92015-02-02 11:27:58 -0500547 setPhonebookPermissionChoice(ACCESS_UNKNOWN);
548 setMessagePermissionChoice(ACCESS_UNKNOWN);
Casper Bonde424681e2015-05-04 22:07:45 -0700549 setSimPermissionChoice(ACCESS_UNKNOWN);
Jason Monk7ce96b92015-02-02 11:27:58 -0500550 mMessageRejectionCount = 0;
551 saveMessageRejectionCount();
552 }
553
554 refresh();
555
556 if (bondState == BluetoothDevice.BOND_BONDED) {
557 if (mDevice.isBluetoothDock()) {
558 onBondingDockConnect();
Jakub Pawlowski0278ab92016-07-20 11:55:48 -0700559 } else if (mDevice.isBondingInitiatedLocally()) {
Jason Monk7ce96b92015-02-02 11:27:58 -0500560 connect(false);
561 }
Jason Monk7ce96b92015-02-02 11:27:58 -0500562 }
563 }
564
565 void setBtClass(BluetoothClass btClass) {
566 if (btClass != null && mBtClass != btClass) {
567 mBtClass = btClass;
568 dispatchAttributesChanged();
569 }
570 }
571
572 public BluetoothClass getBtClass() {
573 return mBtClass;
574 }
575
576 public List<LocalBluetoothProfile> getProfiles() {
577 return Collections.unmodifiableList(mProfiles);
578 }
579
580 public List<LocalBluetoothProfile> getConnectableProfiles() {
581 List<LocalBluetoothProfile> connectableProfiles =
582 new ArrayList<LocalBluetoothProfile>();
583 for (LocalBluetoothProfile profile : mProfiles) {
584 if (profile.isConnectable()) {
585 connectableProfiles.add(profile);
586 }
587 }
588 return connectableProfiles;
589 }
590
591 public List<LocalBluetoothProfile> getRemovedProfiles() {
592 return mRemovedProfiles;
593 }
594
595 public void registerCallback(Callback callback) {
596 synchronized (mCallbacks) {
597 mCallbacks.add(callback);
598 }
599 }
600
601 public void unregisterCallback(Callback callback) {
602 synchronized (mCallbacks) {
603 mCallbacks.remove(callback);
604 }
605 }
606
607 private void dispatchAttributesChanged() {
608 synchronized (mCallbacks) {
609 for (Callback callback : mCallbacks) {
610 callback.onDeviceAttributesChanged();
611 }
612 }
613 }
614
615 @Override
616 public String toString() {
617 return mDevice.toString();
618 }
619
620 @Override
621 public boolean equals(Object o) {
622 if ((o == null) || !(o instanceof CachedBluetoothDevice)) {
623 return false;
624 }
625 return mDevice.equals(((CachedBluetoothDevice) o).mDevice);
626 }
627
628 @Override
629 public int hashCode() {
630 return mDevice.getAddress().hashCode();
631 }
632
633 // This comparison uses non-final fields so the sort order may change
634 // when device attributes change (such as bonding state). Settings
635 // will completely refresh the device list when this happens.
636 public int compareTo(CachedBluetoothDevice another) {
637 // Connected above not connected
638 int comparison = (another.isConnected() ? 1 : 0) - (isConnected() ? 1 : 0);
639 if (comparison != 0) return comparison;
640
641 // Paired above not paired
642 comparison = (another.getBondState() == BluetoothDevice.BOND_BONDED ? 1 : 0) -
643 (getBondState() == BluetoothDevice.BOND_BONDED ? 1 : 0);
644 if (comparison != 0) return comparison;
645
646 // Visible above not visible
647 comparison = (another.mVisible ? 1 : 0) - (mVisible ? 1 : 0);
648 if (comparison != 0) return comparison;
649
650 // Stronger signal above weaker signal
651 comparison = another.mRssi - mRssi;
652 if (comparison != 0) return comparison;
653
654 // Fallback on name
655 return mName.compareTo(another.mName);
656 }
657
658 public interface Callback {
659 void onDeviceAttributesChanged();
660 }
661
662 public int getPhonebookPermissionChoice() {
663 int permission = mDevice.getPhonebookAccessPermission();
664 if (permission == BluetoothDevice.ACCESS_ALLOWED) {
665 return ACCESS_ALLOWED;
666 } else if (permission == BluetoothDevice.ACCESS_REJECTED) {
667 return ACCESS_REJECTED;
668 }
669 return ACCESS_UNKNOWN;
670 }
671
672 public void setPhonebookPermissionChoice(int permissionChoice) {
673 int permission = BluetoothDevice.ACCESS_UNKNOWN;
674 if (permissionChoice == ACCESS_ALLOWED) {
675 permission = BluetoothDevice.ACCESS_ALLOWED;
676 } else if (permissionChoice == ACCESS_REJECTED) {
677 permission = BluetoothDevice.ACCESS_REJECTED;
678 }
679 mDevice.setPhonebookAccessPermission(permission);
680 }
681
682 // Migrates data from old data store (in Settings app's shared preferences) to new (in Bluetooth
683 // app's shared preferences).
684 private void migratePhonebookPermissionChoice() {
685 SharedPreferences preferences = mContext.getSharedPreferences(
686 "bluetooth_phonebook_permission", Context.MODE_PRIVATE);
687 if (!preferences.contains(mDevice.getAddress())) {
688 return;
689 }
690
691 if (mDevice.getPhonebookAccessPermission() == BluetoothDevice.ACCESS_UNKNOWN) {
692 int oldPermission = preferences.getInt(mDevice.getAddress(), ACCESS_UNKNOWN);
693 if (oldPermission == ACCESS_ALLOWED) {
694 mDevice.setPhonebookAccessPermission(BluetoothDevice.ACCESS_ALLOWED);
695 } else if (oldPermission == ACCESS_REJECTED) {
696 mDevice.setPhonebookAccessPermission(BluetoothDevice.ACCESS_REJECTED);
697 }
698 }
699
700 SharedPreferences.Editor editor = preferences.edit();
701 editor.remove(mDevice.getAddress());
702 editor.commit();
703 }
704
705 public int getMessagePermissionChoice() {
706 int permission = mDevice.getMessageAccessPermission();
707 if (permission == BluetoothDevice.ACCESS_ALLOWED) {
708 return ACCESS_ALLOWED;
709 } else if (permission == BluetoothDevice.ACCESS_REJECTED) {
710 return ACCESS_REJECTED;
711 }
712 return ACCESS_UNKNOWN;
713 }
714
715 public void setMessagePermissionChoice(int permissionChoice) {
716 int permission = BluetoothDevice.ACCESS_UNKNOWN;
717 if (permissionChoice == ACCESS_ALLOWED) {
718 permission = BluetoothDevice.ACCESS_ALLOWED;
719 } else if (permissionChoice == ACCESS_REJECTED) {
720 permission = BluetoothDevice.ACCESS_REJECTED;
721 }
722 mDevice.setMessageAccessPermission(permission);
723 }
724
Casper Bonde424681e2015-05-04 22:07:45 -0700725 public int getSimPermissionChoice() {
726 int permission = mDevice.getSimAccessPermission();
727 if (permission == BluetoothDevice.ACCESS_ALLOWED) {
728 return ACCESS_ALLOWED;
729 } else if (permission == BluetoothDevice.ACCESS_REJECTED) {
730 return ACCESS_REJECTED;
731 }
732 return ACCESS_UNKNOWN;
733 }
734
735 void setSimPermissionChoice(int permissionChoice) {
736 int permission = BluetoothDevice.ACCESS_UNKNOWN;
737 if (permissionChoice == ACCESS_ALLOWED) {
738 permission = BluetoothDevice.ACCESS_ALLOWED;
739 } else if (permissionChoice == ACCESS_REJECTED) {
740 permission = BluetoothDevice.ACCESS_REJECTED;
741 }
742 mDevice.setSimAccessPermission(permission);
743 }
744
Jason Monk7ce96b92015-02-02 11:27:58 -0500745 // Migrates data from old data store (in Settings app's shared preferences) to new (in Bluetooth
746 // app's shared preferences).
747 private void migrateMessagePermissionChoice() {
748 SharedPreferences preferences = mContext.getSharedPreferences(
749 "bluetooth_message_permission", Context.MODE_PRIVATE);
750 if (!preferences.contains(mDevice.getAddress())) {
751 return;
752 }
753
754 if (mDevice.getMessageAccessPermission() == BluetoothDevice.ACCESS_UNKNOWN) {
755 int oldPermission = preferences.getInt(mDevice.getAddress(), ACCESS_UNKNOWN);
756 if (oldPermission == ACCESS_ALLOWED) {
757 mDevice.setMessageAccessPermission(BluetoothDevice.ACCESS_ALLOWED);
758 } else if (oldPermission == ACCESS_REJECTED) {
759 mDevice.setMessageAccessPermission(BluetoothDevice.ACCESS_REJECTED);
760 }
761 }
762
763 SharedPreferences.Editor editor = preferences.edit();
764 editor.remove(mDevice.getAddress());
765 editor.commit();
766 }
767
768 /**
769 * @return Whether this rejection should persist.
770 */
771 public boolean checkAndIncreaseMessageRejectionCount() {
772 if (mMessageRejectionCount < MESSAGE_REJECTION_COUNT_LIMIT_TO_PERSIST) {
773 mMessageRejectionCount++;
774 saveMessageRejectionCount();
775 }
776 return mMessageRejectionCount >= MESSAGE_REJECTION_COUNT_LIMIT_TO_PERSIST;
777 }
778
779 private void fetchMessageRejectionCount() {
780 SharedPreferences preference = mContext.getSharedPreferences(
781 MESSAGE_REJECTION_COUNT_PREFS_NAME, Context.MODE_PRIVATE);
782 mMessageRejectionCount = preference.getInt(mDevice.getAddress(), 0);
783 }
784
785 private void saveMessageRejectionCount() {
786 SharedPreferences.Editor editor = mContext.getSharedPreferences(
787 MESSAGE_REJECTION_COUNT_PREFS_NAME, Context.MODE_PRIVATE).edit();
788 if (mMessageRejectionCount == 0) {
789 editor.remove(mDevice.getAddress());
790 } else {
791 editor.putInt(mDevice.getAddress(), mMessageRejectionCount);
792 }
793 editor.commit();
794 }
795
796 private void processPhonebookAccess() {
797 if (mDevice.getBondState() != BluetoothDevice.BOND_BONDED) return;
798
799 ParcelUuid[] uuids = mDevice.getUuids();
800 if (BluetoothUuid.containsAnyUuid(uuids, PbapServerProfile.PBAB_CLIENT_UUIDS)) {
801 // The pairing dialog now warns of phone-book access for paired devices.
802 // No separate prompt is displayed after pairing.
Sanket Padawe78c23762015-06-01 15:55:30 -0700803 if (getPhonebookPermissionChoice() == CachedBluetoothDevice.ACCESS_UNKNOWN) {
Sanket Padawe07533db2015-11-11 15:01:35 -0800804 if (mDevice.getBluetoothClass().getDeviceClass()
Hemant Guptab8d267a2016-06-07 12:53:59 +0530805 == BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE ||
806 mDevice.getBluetoothClass().getDeviceClass()
807 == BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET) {
Sanket Padawe07533db2015-11-11 15:01:35 -0800808 setPhonebookPermissionChoice(CachedBluetoothDevice.ACCESS_ALLOWED);
809 } else {
810 setPhonebookPermissionChoice(CachedBluetoothDevice.ACCESS_REJECTED);
811 }
Sanket Padawe78c23762015-06-01 15:55:30 -0700812 }
Jason Monk7ce96b92015-02-02 11:27:58 -0500813 }
814 }
Jason Monkbe3c5db2015-02-04 13:00:55 -0500815
816 public int getMaxConnectionState() {
817 int maxState = BluetoothProfile.STATE_DISCONNECTED;
818 for (LocalBluetoothProfile profile : getProfiles()) {
819 int connectionStatus = getProfileConnectionState(profile);
820 if (connectionStatus > maxState) {
821 maxState = connectionStatus;
822 }
823 }
824 return maxState;
825 }
826
827 /**
828 * @return resource for string that discribes the connection state of this device.
829 */
830 public int getConnectionSummary() {
831 boolean profileConnected = false; // at least one profile is connected
832 boolean a2dpNotConnected = false; // A2DP is preferred but not connected
Sanket Agarwalf8a1c912016-01-26 20:12:52 -0800833 boolean hfpNotConnected = false; // HFP is preferred but not connected
Jason Monkbe3c5db2015-02-04 13:00:55 -0500834
835 for (LocalBluetoothProfile profile : getProfiles()) {
836 int connectionStatus = getProfileConnectionState(profile);
837
838 switch (connectionStatus) {
839 case BluetoothProfile.STATE_CONNECTING:
840 case BluetoothProfile.STATE_DISCONNECTING:
841 return Utils.getConnectionStateSummary(connectionStatus);
842
843 case BluetoothProfile.STATE_CONNECTED:
844 profileConnected = true;
845 break;
846
847 case BluetoothProfile.STATE_DISCONNECTED:
848 if (profile.isProfileReady()) {
Sanket Agarwalf8a1c912016-01-26 20:12:52 -0800849 if ((profile instanceof A2dpProfile) ||
Sanket Agarwal1bec6a52015-10-21 18:23:27 -0700850 (profile instanceof A2dpSinkProfile)){
Jason Monkbe3c5db2015-02-04 13:00:55 -0500851 a2dpNotConnected = true;
Sanket Agarwalf8a1c912016-01-26 20:12:52 -0800852 } else if ((profile instanceof HeadsetProfile) ||
853 (profile instanceof HfpClientProfile)) {
854 hfpNotConnected = true;
Jason Monkbe3c5db2015-02-04 13:00:55 -0500855 }
856 }
857 break;
858 }
859 }
860
861 if (profileConnected) {
Sanket Agarwalf8a1c912016-01-26 20:12:52 -0800862 if (a2dpNotConnected && hfpNotConnected) {
Jason Monkbe3c5db2015-02-04 13:00:55 -0500863 return R.string.bluetooth_connected_no_headset_no_a2dp;
864 } else if (a2dpNotConnected) {
865 return R.string.bluetooth_connected_no_a2dp;
Sanket Agarwalf8a1c912016-01-26 20:12:52 -0800866 } else if (hfpNotConnected) {
Jason Monkbe3c5db2015-02-04 13:00:55 -0500867 return R.string.bluetooth_connected_no_headset;
868 } else {
869 return R.string.bluetooth_connected;
870 }
871 }
872
873 return getBondState() == BluetoothDevice.BOND_BONDING ? R.string.bluetooth_pairing : 0;
874 }
Jason Monk7ce96b92015-02-02 11:27:58 -0500875}