int getConnectionState(BluetoothDevice device) {
    if (getCurrentState() == mDisconnected) {
      return BluetoothProfile.STATE_DISCONNECTED;
    }

    synchronized (this) {
      IState currentState = getCurrentState();
      if (currentState == mPending) {
        if ((mTargetDevice != null) && mTargetDevice.equals(device)) {
          return BluetoothProfile.STATE_CONNECTING;
        }
        if ((mCurrentDevice != null) && mCurrentDevice.equals(device)) {
          return BluetoothProfile.STATE_DISCONNECTING;
        }
        if ((mIncomingDevice != null) && mIncomingDevice.equals(device)) {
          return BluetoothProfile.STATE_CONNECTING; // incoming connection
        }
        return BluetoothProfile.STATE_DISCONNECTED;
      }

      if (currentState == mConnected) {
        if (mCurrentDevice.equals(device)) {
          return BluetoothProfile.STATE_CONNECTED;
        }
        return BluetoothProfile.STATE_DISCONNECTED;
      } else {
        loge("Bad currentState: " + currentState);
        return BluetoothProfile.STATE_DISCONNECTED;
      }
    }
  }
 // in Connected state
 private void processConnectionEvent(int state, BluetoothDevice device) {
   switch (state) {
     case CONNECTION_STATE_DISCONNECTED:
       mAudioConfigs.remove(device);
       if ((mPlayingDevice != null) && (device.equals(mPlayingDevice))) {
         mPlayingDevice = null;
       }
       if (mCurrentDevice.equals(device)) {
         broadcastConnectionState(
             mCurrentDevice,
             BluetoothProfile.STATE_DISCONNECTED,
             BluetoothProfile.STATE_CONNECTED);
         synchronized (A2dpSinkStateMachine.this) {
           mCurrentDevice = null;
           transitionTo(mDisconnected);
         }
         releasePatch();
         int status = mAudioManager.abandonAudioFocus(mAudioFocusListener);
         if (status == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
           mAudioFocusAcquired = AUDIO_FOCUS_LOSS;
           /* Check if we need to release patch here
            * Would we ever get disconnect directly without
            * Suspend or Stoppped being called before */
         }
       } else {
         loge("Disconnected from unknown device: " + device);
       }
       break;
     default:
       loge("Connection State Device: " + device + " bad state: " + state);
       break;
   }
 }
  private boolean msgTypeDocked(BluetoothDevice device, final int state, final int startId) {
    if (DEBUG) {
      // TODO figure out why hasMsg always returns false if device
      // is supplied
      Log.d(
          TAG,
          "1 Has undock perm msg = "
              + mServiceHandler.hasMessages(MSG_TYPE_UNDOCKED_PERMANENT, mDevice));
      Log.d(
          TAG,
          "2 Has undock perm msg = "
              + mServiceHandler.hasMessages(MSG_TYPE_UNDOCKED_PERMANENT, device));
    }

    mServiceHandler.removeMessages(MSG_TYPE_UNDOCKED_PERMANENT);
    mServiceHandler.removeMessages(MSG_TYPE_DISABLE_BT);
    getPrefs().edit().remove(KEY_DISABLE_BT).apply();

    if (device != null) {
      if (!device.equals(mDevice)) {
        if (mDevice != null) {
          // Not expected. Cleanup/undock existing
          handleUndocked(mDevice);
        }

        mDevice = device;

        // Register first in case LocalBluetoothProfileManager
        // becomes ready after isManagerReady is called and it
        // would be too late to register a service listener.
        mProfileManager.addServiceListener(this);
        if (mProfileManager.isManagerReady()) {
          handleDocked(device, state, startId);
          // Not needed after all
          mProfileManager.removeServiceListener(this);
        } else {
          final BluetoothDevice d = device;
          mRunnable =
              new Runnable() {
                public void run() {
                  handleDocked(d, state, startId); // FIXME: WTF runnable here?
                }
              };
          return true;
        }
      }
    } else {
      // display dialog to enable dock for media audio only in the case of low end docks and
      // if not already selected by user
      int dockAudioMediaEnabled =
          Settings.Global.getInt(
              getContentResolver(), Settings.Global.DOCK_AUDIO_MEDIA_ENABLED, -1);
      if (dockAudioMediaEnabled == -1 && state == Intent.EXTRA_DOCK_STATE_LE_DESK) {
        handleDocked(null, state, startId);
        return true;
      }
    }
    return false;
  }
예제 #4
0
 boolean isPlaying(BluetoothDevice device) {
   synchronized (this) {
     if (device.equals(mPlayingA2dpDevice)) {
       return true;
     }
   }
   return false;
 }
 boolean isPlaying(BluetoothDevice device) {
   synchronized (this) {
     if ((mPlayingDevice != null) && (device.equals(mPlayingDevice))) {
       return true;
     }
   }
   return false;
 }
 private void adjustOtherHeadsetPriorities(BluetoothDevice connectedDevice) {
   for (BluetoothDevice device : mAdapter.getBondedDevices()) {
     if (getPriority(device) >= BluetoothHeadset.PRIORITY_AUTO_CONNECT
         && !device.equals(connectedDevice)) {
       setPriority(device, BluetoothHeadset.PRIORITY_ON);
     }
   }
 }
 public Object map(BluetoothDevice device) {
   if (isAvailable()) {
     // 먼저 클라이언트 훑어보고
     for (int i = 0; i < clientDevices.length; i++) {
       if (device.equals(clientDevices[i]) == true) {
         return players[i]; // 플레이어 리턴
       }
     }
     // 윷 훑어봄
     for (int i = 0; i < yutDevices.length; i++) {
       if (device.equals(yutDevices[i]) == true) {
         return yutGameTools[i]; // 윷 리턴
       }
     }
   }
   return null;
 }
 void informAvrcpStatePlaying(BluetoothDevice device) {
   if ((mPlayingDevice != null) && (device.equals(mPlayingDevice))) {
     log(" AVRCP State is Playing");
     /* If call is ongoing, Focus already acquired, no need to
      * send this info to bluedroid
      */
     if (mAudioFocusAcquired == AUDIO_FOCUS_LOSS_TRANSIENT) SendPassThruPause(device);
     if ((USE_AUDIOTRACK) && (mAudioFocusAcquired == AUDIO_FOCUS_LOSS))
       informAudioFocusStateNative(STATE_FOCUS_READY);
   }
 }
  private synchronized void getSdpRecordsAndConnect(BluetoothDevice device) {
    if (!device.equals(getCurrentDevice())) {
      // stale
      return;
    }

    // Check if incoming connection has already connected.
    if (mRemoteHeadsets.get(device).mState == BluetoothHeadset.STATE_CONNECTED) {
      return;
    }

    ParcelUuid[] uuids = device.getUuids();
    int type = BluetoothHandsfree.TYPE_UNKNOWN;
    if (uuids != null) {
      if (BluetoothUuid.isUuidPresent(uuids, BluetoothUuid.Handsfree)) {
        log("SDP UUID: TYPE_HANDSFREE");
        type = BluetoothHandsfree.TYPE_HANDSFREE;
        mRemoteHeadsets.get(device).mHeadsetType = type;
        int channel = device.getServiceChannel(BluetoothUuid.Handsfree);
        mConnectThread = new RfcommConnectThread(device, channel, type);
        if (mAdapter.isDiscovering()) {
          mAdapter.cancelDiscovery();
        }
        mConnectThread.start();
        if (getPriority(device) < BluetoothHeadset.PRIORITY_AUTO_CONNECT) {
          setPriority(device, BluetoothHeadset.PRIORITY_AUTO_CONNECT);
        }
        return;
      } else if (BluetoothUuid.isUuidPresent(uuids, BluetoothUuid.HSP)) {
        log("SDP UUID: TYPE_HEADSET");
        type = BluetoothHandsfree.TYPE_HEADSET;
        mRemoteHeadsets.get(device).mHeadsetType = type;
        int channel = device.getServiceChannel(BluetoothUuid.HSP);
        mConnectThread = new RfcommConnectThread(device, channel, type);
        if (mAdapter.isDiscovering()) {
          mAdapter.cancelDiscovery();
        }
        mConnectThread.start();
        if (getPriority(device) < BluetoothHeadset.PRIORITY_AUTO_CONNECT) {
          setPriority(device, BluetoothHeadset.PRIORITY_AUTO_CONNECT);
        }
        return;
      }
    }
    log("SDP UUID: TYPE_UNKNOWN");
    mRemoteHeadsets.get(device).mHeadsetType = type;
    setState(
        device,
        BluetoothHeadset.STATE_DISCONNECTED,
        BluetoothHeadset.RESULT_FAILURE,
        BluetoothHeadset.LOCAL_DISCONNECT);
    return;
  }
 @Override
 public void onReceive(Context context, Intent intent) {
   String action = intent.getAction();
   if (action.equals(BluetoothDevice.ACTION_CONNECTION_ACCESS_CANCEL)) {
     int requestType =
         intent.getIntExtra(
             BluetoothDevice.EXTRA_ACCESS_REQUEST_TYPE,
             BluetoothDevice.REQUEST_TYPE_PHONEBOOK_ACCESS);
     if (requestType != mRequestType) return;
     BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
     if (mDevice.equals(device)) dismissDialog();
   }
 }
예제 #11
0
  private boolean isPaired(BluetoothDevice deviceFound) {

    boolean isPaired = false;

    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    for (BluetoothDevice pariedDevice : pairedDevices) {

      if (pariedDevice.equals(deviceFound)) {
        Toast.makeText(PairingActivity.this, "이미 패어링 되어있음", Toast.LENGTH_SHORT).show();
        isPaired = true;
      }
    }
    return isPaired;
  }
  private void handleBluetoothStateOn(int startId) {
    if (mPendingDevice != null) {
      if (mPendingDevice.equals(mDevice)) {
        if (DEBUG) {
          Log.d(TAG, "applying settings");
        }
        applyBtSettings(mPendingDevice, mPendingStartId);
      } else if (DEBUG) {
        Log.d(TAG, "mPendingDevice  (" + mPendingDevice + ") != mDevice (" + mDevice + ')');
      }

      mPendingDevice = null;
      DockEventReceiver.finishStartingService(this, mPendingStartId);
    } else {
      final SharedPreferences prefs = getPrefs();
      if (DEBUG) {
        Log.d(
            TAG,
            "A DISABLE_BT_WHEN_UNDOCKED = "
                + prefs.getBoolean(KEY_DISABLE_BT_WHEN_UNDOCKED, false));
      }
      // Reconnect if docked and bluetooth was enabled by user.
      Intent i = registerReceiver(null, new IntentFilter(Intent.ACTION_DOCK_EVENT));
      if (i != null) {
        int state = i.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED);
        if (state != Intent.EXTRA_DOCK_STATE_UNDOCKED) {
          BluetoothDevice device = i.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
          if (device != null) {
            connectIfEnabled(device);
          }
        } else if (prefs.getBoolean(KEY_DISABLE_BT, false) && mLocalAdapter.disable()) {
          mPendingTurnOffStartId = startId;
          prefs.edit().remove(KEY_DISABLE_BT).apply();
          return;
        }
      }
    }

    if (mPendingTurnOnStartId != INVALID_STARTID) {
      DockEventReceiver.finishStartingService(this, mPendingTurnOnStartId);
      mPendingTurnOnStartId = INVALID_STARTID;
    }

    DockEventReceiver.finishStartingService(this, startId);
  }
        @Override
        public void onReceive(Context context, Intent intent) {
          // TODO: put this in callback instead of receiving

          if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            onBluetoothStateChanged(mLocalManager.getBluetoothState());
          } else if (intent.getAction().equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
              && mScreenType == SCREEN_TYPE_DEVICEPICKER) {
            int bondState =
                intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
            if (bondState == BluetoothDevice.BOND_BONDED) {
              BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
              if (device.equals(mSelectedDevice)) {
                sendDevicePickedIntent(device);
                finish();
              }
            }
          }
        }
  synchronized boolean hasOtherConnectedDevices(BluetoothDevice dock) {
    Collection<CachedBluetoothDevice> cachedDevices = mDeviceManager.getCachedDevicesCopy();
    Set<BluetoothDevice> btDevices = mLocalAdapter.getBondedDevices();
    if (btDevices == null || cachedDevices == null || btDevices.isEmpty()) {
      return false;
    }
    if (DEBUG) {
      Log.d(TAG, "btDevices = " + btDevices.size());
      Log.d(TAG, "cachedDeviceUIs = " + cachedDevices.size());
    }

    for (CachedBluetoothDevice deviceUI : cachedDevices) {
      BluetoothDevice btDevice = deviceUI.getDevice();
      if (!btDevice.equals(dock) && btDevices.contains(btDevice) && deviceUI.isConnected()) {
        if (DEBUG) Log.d(TAG, "connected deviceUI = " + deviceUI.getName());
        return true;
      }
    }
    return false;
  }
  private synchronized void handleUnexpectedDisconnect(
      BluetoothDevice disconnectedDevice, LocalBluetoothProfile profile, int startId) {
    if (DEBUG) {
      Log.d(TAG, "handling failed connect for " + disconnectedDevice);
    }

    // Reconnect if docked.
    if (disconnectedDevice != null) {
      // registerReceiver can't be called from a BroadcastReceiver
      Intent intent = registerReceiver(null, new IntentFilter(Intent.ACTION_DOCK_EVENT));
      if (intent != null) {
        int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED);
        if (state != Intent.EXTRA_DOCK_STATE_UNDOCKED) {
          BluetoothDevice dockedDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
          if (dockedDevice != null && dockedDevice.equals(disconnectedDevice)) {
            CachedBluetoothDevice cachedDevice = getCachedBluetoothDevice(dockedDevice);
            cachedDevice.connectProfile(profile);
          }
        }
      }
    }

    DockEventReceiver.finishStartingService(this, startId);
  }
  private synchronized void applyBtSettings(BluetoothDevice device, int startId) {
    if (device == null || mProfiles == null || mCheckedItems == null || mLocalAdapter == null) {
      return;
    }

    // Turn on BT if something is enabled
    for (boolean enable : mCheckedItems) {
      if (enable) {
        int btState = mLocalAdapter.getBluetoothState();
        if (DEBUG) {
          Log.d(TAG, "BtState = " + btState);
        }
        // May have race condition as the phone comes in and out and in the dock.
        // Always turn on BT
        mLocalAdapter.enable();

        // if adapter was previously OFF, TURNING_OFF, or TURNING_ON
        if (btState != BluetoothAdapter.STATE_ON) {
          if (mPendingDevice != null && mPendingDevice.equals(mDevice)) {
            return;
          }

          mPendingDevice = device;
          mPendingStartId = startId;
          if (btState != BluetoothAdapter.STATE_TURNING_ON) {
            getPrefs().edit().putBoolean(KEY_DISABLE_BT_WHEN_UNDOCKED, true).apply();
          }
          return;
        }
      }
    }

    mPendingDevice = null;

    boolean callConnect = false;
    CachedBluetoothDevice cachedDevice = getCachedBluetoothDevice(device);
    for (int i = 0; i < mProfiles.length; i++) {
      LocalBluetoothProfile profile = mProfiles[i];
      if (DEBUG) Log.d(TAG, profile.toString() + " = " + mCheckedItems[i]);

      if (mCheckedItems[i]) {
        // Checked but not connected
        callConnect = true;
      } else if (!mCheckedItems[i]) {
        // Unchecked, may or may not be connected.
        int status = profile.getConnectionStatus(cachedDevice.getDevice());
        if (status == BluetoothProfile.STATE_CONNECTED) {
          if (DEBUG) Log.d(TAG, "applyBtSettings - Disconnecting");
          cachedDevice.disconnect(mProfiles[i]);
        }
      }
      profile.setPreferred(device, mCheckedItems[i]);
      if (DEBUG) {
        if (mCheckedItems[i] != profile.isPreferred(device)) {
          Log.e(TAG, "Can't save preferred value");
        }
      }
    }

    if (callConnect) {
      if (DEBUG) Log.d(TAG, "applyBtSettings - Connecting");
      cachedDevice.connect(false);
    }
  }
예제 #17
0
        //   @Override
        public void handleMessage(Message msg) {
          Instance instance;
          ArrayList<Instance> instances;
          int result = MAP.RESULT_ERROR;
          String addr;
          BluetoothDevice device = null;
          log("message received: " + msg.what);

          switch (msg.what) {
            case MAP_SERVER_ENABLE_CNF:
              /*to do: set state*/
              setState(BluetoothMap.STATE_ENABLED);
              sendMessage(obtainMessage(MAP_REGISTER_SERVER));
              onStateChanged(BluetoothMap.STATE_ENABLED);
              break;
            case MAP_SERVER_DISABLE_CNF:
              /*to do: set state*/
              mManager.removeAllInstances();
              setState(BluetoothMap.STATE_DISABLED);
              onStateChanged(BluetoothMap.STATE_DISABLED);
              deinitServer();
              break;
            case MAP_SERVER_REGISTER_CNF:
              instance = mManager.getInstanceById(msg.arg1);
              if (msg.arg2 >= 0 && instance != null) {
                instance.onInstanceRegistered();
              } else {
                mManager.removeInstance(msg.arg1);
              }
              break;
            case MAP_SERVER_DEREGISTER_CNF:
              instance = mManager.getInstanceById(msg.arg1);
              if (instance != null) {
                instance.onInstanceDeregistered();
              }
              mManager.removeInstance(msg.arg1);
              break;
            case MAP_SERVER_CONNECT_IND:
              instance = mManager.getInstanceById(msg.arg1);
              device = mAdapter.getRemoteDevice((String) msg.obj);
              if (instance != null) {
                instance.onDeviceConnected(device);
              } else {
                log("invalid instance ID is received");
                return;
              }

              mNotification.createNotification(
                  BluetoothMapNotification.ALERT_TYPE_CONNECT, device, true);
              break;
            case MAP_SERVER_DISCONNECT_CNF:
            case MAP_SERVER_DISCONNECT_IND:
              instance = mManager.getInstanceById(msg.arg1);
              device = mAdapter.getRemoteDevice((String) msg.obj);
              if (instance != null) {
                instance.onDeviceDisconnected(device);
              } else {
                log("invalid instance ID is received:" + msg.arg1);
              }
              if (mManager.getState(device) == BluetoothMap.STATE_DISCONNECTED) {
                mNotification.removeNotification(
                    BluetoothMapNotification.ALERT_TYPE_CONNECT, device);
              }
              if (mState == BluetoothMap.STATE_DISABLING) {
                removeMessages(MAP_DISCONNECT_INSTANCE_TIMEOUT, instance);
                disable(false);
              }
              break;
            case MAP_SERVER_SET_FOLDER:
              instance = mManager.getInstanceById(msg.arg1);
              if (msg.obj == null || instance == null) {
                log("SetFolderRequest or instance is null");
                return;
              }
              SetFolderRequest setFolderReq = (SetFolderRequest) msg.obj;
              result = instance.setFolder(setFolderReq);
              setFolderResponse(setFolderReq.getAddress(), msg.arg1, result);
              break;
            case MAP_SERVER_UPDATE_INBOX:
              instance = mManager.getInstanceById(msg.arg1);
              if (msg.obj == null || instance == null) {
                log("address or instance is null");
                return;
              }
              addr = (String) msg.obj;
              result = instance.updateInbox();
              updateInboxResponse(addr, msg.arg1, result);
              break;

            case MAP_SERVER_GET_MESSAGE_LIST:
              instance = mManager.getInstanceById(msg.arg1);
              if (msg.obj == null || instance == null) {
                log("address is null or instance is null");
                return;
              }
              MessageListRequest msgListReq = (MessageListRequest) msg.obj;
              MessageListObject msgListRsp = instance.getMessagelist(msgListReq);
              addr = msgListReq.getAddress();
              getMessageListResponse(addr, msg.arg1, MAP.RESULT_OK, msgListRsp);
              break;

            case MAP_SERVER_GET_FOLDER_LIST:
              instance = mManager.getInstanceById(msg.arg1);
              if (msg.obj == null || instance == null) {
                log("address is null or instance is null");
                return;
              }
              FolderListObject[] fodlerlistrsp = null;
              FolderListRequest folderListReq = (FolderListRequest) msg.obj;
              addr = folderListReq.getAddress();
              device = mAdapter.getRemoteDevice(addr);
              if (device != null && device.equals(instance.getDevice())) {
                fodlerlistrsp = instance.getFolderlist(folderListReq);
              }
              getFolderListResponse(addr, msg.arg1, MAP.RESULT_OK, fodlerlistrsp);
              break;
            case MAP_SERVER_GET_MESSAGE:
              instance = mManager.getInstanceById(msg.arg1);
              if (msg.obj == null || instance == null) {
                log("address is null or instance is null");
                return;
              }
              MessageRequest messagereq = (MessageRequest) msg.obj;
              BMessageObject messagersp = instance.getMessage(messagereq);
              if (messagersp != null) {
                result = MAP.RESULT_OK;
              }
              addr = messagereq.getAddress();
              getMessageResponse(addr, msg.arg1, result, messagersp);
              /*	if (messagersp != null) {
              messagersp.reset();
              } */
              break;
            case MAP_SERVER_SET_NOTIFICATION:
              instance = mManager.getInstanceById(msg.arg1);
              if (msg.obj == null || instance == null) {
                log("address is null or instance is null");
                return;
              }
              result = MAP.RESULT_OK;
              setNotificationRegResponse((String) msg.obj, msg.arg1, result);
              break;
            case MAP_SERVER_SEND_REPORT_CNF:
              instance = mManager.getInstanceById(msg.arg1);
              if (msg.obj == null || instance == null) {
                log("address is null or instance is null");
                return;
              }
              mEventManager.onEventSentCompleted();
              break;
            case MAP_SERVER_AUTHORIZE_IND:
              // TODO: launch an alert to notify user that a device is trying to access local
              // resource
              if (msg.obj == null) {
                log("address is null");
                return;
              }
              device = mAdapter.getRemoteDevice((String) msg.obj);
              int state = mNotification.getDeviceState(device);
              if (state == BluetoothMap.STATE_NONE) {
                mNotification.createNotification(
                    BluetoothMapNotification.ALERT_TYPE_AUTHORIZE, device, true);
              } else if (state == BluetoothMap.STATE_CONNECTED) {
                // already connected
                authorizeResponse(device, true);
              } else if (state == BluetoothMap.STATE_AUTHORIZING) {
                log("the device is authorizing");
                // do nothing
              } else {
                log("unexpected state : " + state);
                authorizeResponse(device, false);
              }
              break;
            case MAP_SERVER_PUSH_MESSAGE:
              instance = mManager.getInstanceById(msg.arg1);
              if (msg.obj == null || instance == null) {
                log("address is null or instance is null");
                return;
              }
              BMessageObject bMessageobject = instance.getBMessageObject();
              bMessageobject.reset();
              if (parseMessage((String) msg.obj, msg.arg1, bMessageobject) == false) {
                result = MAP.RESULT_ERROR;
              } else {
                if (instance.pushMessage(bMessageobject)) {
                  result = MAP.RESULT_OK;
                } else {
                  result = MAP.RESULT_ERROR;
                }
              }
              sendMessageResponse((String) msg.obj, msg.arg1, result, bMessageobject.getHandle());
              break;
              /*		case MAP_SERVER_DELETE_MESSAGE:
              instance = mManager.getInstanceById(msg.arg1);
              if (msg.obj == null || instance == null) {
              	log("address is null or instance is null");
              	return;
              }
              //BMessageObject bMessageobject = instance.getBMessageObject();
              //sendMessageResponse((String) msg.obj, msg.arg1 ,bMessageobject);
              if(instance.deleteMessage(msg.arg1, msg.arg2)){
              	result = MAP.RESULT_OK;
              } else {
              	result = MAP.RESULT_ERROR;
              }
              setMessageStatusResponse((String)msg.obj, msg.arg1, result);
              break;
              */
            case MAP_SERVER_SET_MESSAGE_STATUS:
              instance = mManager.getInstanceById(msg.arg1);
              if (msg.obj == null || instance == null) {
                log("address is null or instance is null");
                return;
              }
              StatusSwitchRequest req = (StatusSwitchRequest) msg.obj;
              if (instance.setMessageStatus(req)) {
                result = MAP.RESULT_OK;
              } else {
                result = MAP.RESULT_ERROR;
              }
              addr = req.getAddress();
              setMessageStatusResponse(addr, msg.arg1, result);
              break;
            case MAP_SERVER_MNS_DISCONNCET_CNF:
              device = mAdapter.getRemoteDevice((String) msg.obj);
              instances = mManager.getInstanceByDevice(device);
              for (int i = 0; i < instances.size(); i++) {
                instances.get(i).deregisterCallback();
              }
              if (mState == BluetoothMap.STATE_DISABLING) {
                disable(false);
              }
              break;
            case MAP_SERVER_MNS_CONNECT_CNF:
              if (msg.arg1 == MAP.RESULT_ERROR) {
                log("fail to set up mns connection");
              } else {
                device = mAdapter.getRemoteDevice((String) msg.obj);
                instances = mManager.getInstanceByDevice(device);
                for (int i = 0; i < instances.size(); i++) {
                  instances.get(i).registerCallback(mEventManager);
                }
              }
              break;
            case MAP_REGISTER_SERVER:
              if (NetworkUtil.isPhoneRadioReady()) {
                registerServer();
              } else {
                mRegSrvCnt++;
                if (mRegSrvCnt < 10) {
                  sendMessageDelayed(
                      obtainMessage(MAP_REGISTER_SERVER), REGISTER_SERVER_DELAY_DURATION);
                } else {
                  log("Network is still not ready after 10s, so phone radio maybe is in error");
                }
              }
              break;
            case MAP_DISCONNECT_INSTANCE_TIMEOUT:
              instance = (Instance) msg.obj;
              if (instance != null) {
                instance.onDeviceDisconnected(instance.getDevice());
                if (mState == BluetoothMap.STATE_DISABLING) {
                  disable(false);
                }
              }
              break;
            default:
              log("Unrecognized message");
          }
        }
 private void onAudioFocusRequested(byte[] address) {
   BluetoothDevice device = getDevice(address);
   if (device.equals(mPlayingDevice)) requestAudioFocus(true, device, 0);
 }
        @Override
        public void onReceive(Context context, Intent intent) {
          String action = intent.getAction();
          BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

          BluetoothDevice currDevice = getCurrentDevice();
          int state = BluetoothHeadset.STATE_DISCONNECTED;
          if (currDevice != null) {
            state = mRemoteHeadsets.get(currDevice).mState;
          }

          if ((state == BluetoothHeadset.STATE_CONNECTED
                  || state == BluetoothHeadset.STATE_CONNECTING)
              && action.equals(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED)
              && device.equals(currDevice)) {
            try {
              mBinder.disconnectHeadset(currDevice);
            } catch (RemoteException e) {
            }
          } else if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            switch (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)) {
              case BluetoothAdapter.STATE_ON:
                adjustPriorities();
                mAg.start(mIncomingConnectionHandler);
                mBtHandsfree.onBluetoothEnabled();
                break;
              case BluetoothAdapter.STATE_TURNING_OFF:
                mBtHandsfree.onBluetoothDisabled();
                mAg.stop();
                if (currDevice != null) {
                  setState(
                      currDevice,
                      BluetoothHeadset.STATE_DISCONNECTED,
                      BluetoothHeadset.RESULT_FAILURE,
                      BluetoothHeadset.LOCAL_DISCONNECT);
                }
                break;
            }
          } else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
            int bondState =
                intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
            switch (bondState) {
              case BluetoothDevice.BOND_BONDED:
                if (getPriority(device) == BluetoothHeadset.PRIORITY_UNDEFINED) {
                  setPriority(device, BluetoothHeadset.PRIORITY_ON);
                }
                break;
              case BluetoothDevice.BOND_NONE:
                setPriority(device, BluetoothHeadset.PRIORITY_UNDEFINED);
                break;
            }
          } else if (action.equals(AudioManager.VOLUME_CHANGED_ACTION)) {
            int streamType = intent.getIntExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, -1);
            if (streamType == AudioManager.STREAM_BLUETOOTH_SCO) {
              mBtHandsfree.sendScoGainUpdate(
                  intent.getIntExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, 0));
            }

          } else if (action.equals(BluetoothDevice.ACTION_UUID)) {
            if (device.equals(mDeviceSdpQuery) && device.equals(currDevice)) {
              // We have got SDP records for the device we are interested in.
              getSdpRecordsAndConnect(device);
            }
          }
        }