Home | History | Annotate | Download | only in handover
      1 /*
      2  * Copyright (C) 2012 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 
     17 package com.android.nfc.handover;
     18 
     19 import java.nio.BufferUnderflowException;
     20 import java.nio.ByteBuffer;
     21 import java.nio.charset.Charset;
     22 import java.util.ArrayList;
     23 import java.util.Arrays;
     24 import java.util.HashMap;
     25 import java.util.Random;
     26 
     27 import android.bluetooth.BluetoothAdapter;
     28 import android.bluetooth.BluetoothDevice;
     29 import android.content.BroadcastReceiver;
     30 import android.content.ComponentName;
     31 import android.content.Context;
     32 import android.content.Intent;
     33 import android.content.IntentFilter;
     34 import android.content.ServiceConnection;
     35 import android.net.Uri;
     36 import android.nfc.FormatException;
     37 import android.nfc.NdefMessage;
     38 import android.nfc.NdefRecord;
     39 import android.os.Bundle;
     40 import android.os.Handler;
     41 import android.os.IBinder;
     42 import android.os.Message;
     43 import android.os.Messenger;
     44 import android.os.RemoteException;
     45 import android.os.UserHandle;
     46 import android.util.Log;
     47 
     48 /**
     49  * Manages handover of NFC to other technologies.
     50  */
     51 public class HandoverManager {
     52     static final String TAG = "NfcHandover";
     53     static final boolean DBG = true;
     54 
     55     static final String ACTION_WHITELIST_DEVICE =
     56             "android.btopp.intent.action.WHITELIST_DEVICE";
     57 
     58     static final byte[] TYPE_NOKIA = "nokia.com:bt".getBytes(Charset.forName("US_ASCII"));
     59     static final byte[] TYPE_BT_OOB = "application/vnd.bluetooth.ep.oob".
     60             getBytes(Charset.forName("US_ASCII"));
     61 
     62     static final byte[] RTD_COLLISION_RESOLUTION = {0x63, 0x72}; // "cr";
     63 
     64     static final int CARRIER_POWER_STATE_INACTIVE = 0;
     65     static final int CARRIER_POWER_STATE_ACTIVE = 1;
     66     static final int CARRIER_POWER_STATE_ACTIVATING = 2;
     67     static final int CARRIER_POWER_STATE_UNKNOWN = 3;
     68 
     69     static final int MSG_HANDOVER_COMPLETE = 0;
     70     static final int MSG_HEADSET_CONNECTED = 1;
     71     static final int MSG_HEADSET_NOT_CONNECTED = 2;
     72 
     73     final Context mContext;
     74     final BluetoothAdapter mBluetoothAdapter;
     75     final Messenger mMessenger = new Messenger (new MessageHandler());
     76 
     77     final Object mLock = new Object();
     78     // Variables below synchronized on mLock
     79     HashMap<Integer, PendingHandoverTransfer> mPendingTransfers;
     80     ArrayList<Message> mPendingServiceMessages;
     81     boolean mBluetoothHeadsetPending;
     82     boolean mBluetoothHeadsetConnected;
     83     boolean mBluetoothEnabledByNfc;
     84     int mHandoverTransferId;
     85     Messenger mService = null;
     86     boolean mBinding = false;
     87     boolean mBound;
     88     String mLocalBluetoothAddress;
     89     boolean mEnabled;
     90 
     91     static class BluetoothHandoverData {
     92         public boolean valid = false;
     93         public BluetoothDevice device;
     94         public String name;
     95         public boolean carrierActivating = false;
     96     }
     97 
     98     class MessageHandler extends Handler {
     99         @Override
    100         public void handleMessage(Message msg) {
    101             synchronized (mLock) {
    102                 switch (msg.what) {
    103                     case MSG_HANDOVER_COMPLETE:
    104                         int transferId = msg.arg1;
    105                         Log.d(TAG, "Completed transfer id: " + Integer.toString(transferId));
    106                         if (mPendingTransfers.containsKey(transferId)) {
    107                             mPendingTransfers.remove(transferId);
    108                         } else {
    109                             Log.e(TAG, "Could not find completed transfer id: " + Integer.toString(transferId));
    110                         }
    111                         break;
    112                     case MSG_HEADSET_CONNECTED:
    113                         mBluetoothEnabledByNfc = msg.arg1 != 0;
    114                         mBluetoothHeadsetConnected = true;
    115                         mBluetoothHeadsetPending = false;
    116                         break;
    117                     case MSG_HEADSET_NOT_CONNECTED:
    118                         mBluetoothEnabledByNfc = false; // No need to maintain this state any longer
    119                         mBluetoothHeadsetConnected = false;
    120                         mBluetoothHeadsetPending = false;
    121                         break;
    122                     default:
    123                         break;
    124                 }
    125                 unbindServiceIfNeededLocked(false);
    126             }
    127         }
    128     };
    129 
    130     private ServiceConnection mConnection = new ServiceConnection() {
    131         @Override
    132         public void onServiceConnected(ComponentName name, IBinder service) {
    133             synchronized (mLock) {
    134                 mService = new Messenger(service);
    135                 mBinding = false;
    136                 mBound = true;
    137                 // Register this client and transfer last known service state
    138                 Message msg = Message.obtain(null, HandoverService.MSG_REGISTER_CLIENT);
    139                 msg.arg1 = mBluetoothEnabledByNfc ? 1 : 0;
    140                 msg.arg2 = mBluetoothHeadsetConnected ? 1 : 0;
    141                 msg.replyTo = mMessenger;
    142                 try {
    143                     mService.send(msg);
    144                 } catch (RemoteException e) {
    145                     Log.e(TAG, "Failed to register client");
    146                 }
    147                 // Send all queued messages
    148                 while (!mPendingServiceMessages.isEmpty()) {
    149                     msg = mPendingServiceMessages.remove(0);
    150                     try {
    151                         mService.send(msg);
    152                     } catch (RemoteException e) {
    153                         Log.e(TAG, "Failed to send queued message to service");
    154                     }
    155                 }
    156             }
    157         }
    158 
    159         @Override
    160         public void onServiceDisconnected(ComponentName name) {
    161             synchronized (mLock) {
    162                 Log.d(TAG, "Service disconnected");
    163                 if (mService != null) {
    164                     try {
    165                         Message msg = Message.obtain(null, HandoverService.MSG_DEREGISTER_CLIENT);
    166                         msg.replyTo = mMessenger;
    167                         mService.send(msg);
    168                     } catch (RemoteException e) {
    169                         // Service may have crashed - ignore
    170                     }
    171                 }
    172                 mService = null;
    173                 mBound = false;
    174                 mBluetoothHeadsetPending = false;
    175                 mPendingTransfers.clear();
    176                 mPendingServiceMessages.clear();
    177             }
    178         }
    179     };
    180 
    181     public HandoverManager(Context context) {
    182         mContext = context;
    183         mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    184 
    185         mPendingTransfers = new HashMap<Integer, PendingHandoverTransfer>();
    186         mPendingServiceMessages = new ArrayList<Message>();
    187 
    188         IntentFilter filter = new IntentFilter(Intent.ACTION_USER_SWITCHED);
    189         mContext.registerReceiver(mReceiver, filter, null, null);
    190 
    191         mEnabled = true;
    192         mBluetoothEnabledByNfc = false;
    193     }
    194 
    195     final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    196         @Override
    197         public void onReceive(Context context, Intent intent) {
    198             String action = intent.getAction();
    199             if (action.equals(Intent.ACTION_USER_SWITCHED)) {
    200                 // Just force unbind the service.
    201                 unbindServiceIfNeededLocked(true);
    202             }
    203         }
    204     };
    205 
    206     /**
    207      * @return whether the service was bound to successfully
    208      */
    209     boolean bindServiceIfNeededLocked() {
    210         if (!mBinding) {
    211             Log.d(TAG, "Binding to handover service");
    212             boolean bindSuccess = mContext.bindServiceAsUser(new Intent(mContext,
    213                     HandoverService.class), mConnection, Context.BIND_AUTO_CREATE,
    214                     UserHandle.CURRENT);
    215             mBinding = bindSuccess;
    216             return bindSuccess;
    217         } else {
    218            // A previous bind is pending
    219            return true;
    220         }
    221     }
    222 
    223     void unbindServiceIfNeededLocked(boolean force) {
    224         // If no service operation is pending, unbind
    225         if (mBound && (force || (!mBluetoothHeadsetPending && mPendingTransfers.isEmpty()))) {
    226             Log.d(TAG, "Unbinding from service.");
    227             mContext.unbindService(mConnection);
    228             mBound = false;
    229             mPendingServiceMessages.clear();
    230             mBluetoothHeadsetPending = false;
    231             mPendingTransfers.clear();
    232         }
    233         return;
    234     }
    235 
    236     static NdefRecord createCollisionRecord() {
    237         byte[] random = new byte[2];
    238         new Random().nextBytes(random);
    239         return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, RTD_COLLISION_RESOLUTION, null, random);
    240     }
    241 
    242     NdefRecord createBluetoothAlternateCarrierRecord(boolean activating) {
    243         byte[] payload = new byte[4];
    244         payload[0] = (byte) (activating ? CARRIER_POWER_STATE_ACTIVATING :
    245             CARRIER_POWER_STATE_ACTIVE);  // Carrier Power State: Activating or active
    246         payload[1] = 1;   // length of carrier data reference
    247         payload[2] = 'b'; // carrier data reference: ID for Bluetooth OOB data record
    248         payload[3] = 0;  // Auxiliary data reference count
    249         return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_ALTERNATIVE_CARRIER, null, payload);
    250     }
    251 
    252     NdefRecord createBluetoothOobDataRecord() {
    253         byte[] payload = new byte[8];
    254         // Note: this field should be little-endian per the BTSSP spec
    255         // The Android 4.1 implementation used big-endian order here.
    256         // No single Android implementation has ever interpreted this
    257         // length field when parsing this record though.
    258         payload[0] = (byte) (payload.length & 0xFF);
    259         payload[1] = (byte) ((payload.length >> 8) & 0xFF);
    260 
    261         synchronized (mLock) {
    262             if (mLocalBluetoothAddress == null) {
    263                 mLocalBluetoothAddress = mBluetoothAdapter.getAddress();
    264             }
    265 
    266             byte[] addressBytes = addressToReverseBytes(mLocalBluetoothAddress);
    267             System.arraycopy(addressBytes, 0, payload, 2, 6);
    268         }
    269 
    270         return new NdefRecord(NdefRecord.TNF_MIME_MEDIA, TYPE_BT_OOB, new byte[]{'b'}, payload);
    271     }
    272 
    273     public void setEnabled(boolean enabled) {
    274         synchronized (mLock) {
    275             mEnabled = enabled;
    276         }
    277     }
    278     public boolean isHandoverSupported() {
    279         return (mBluetoothAdapter != null);
    280     }
    281 
    282     public NdefMessage createHandoverRequestMessage() {
    283         if (mBluetoothAdapter == null) return null;
    284 
    285         return new NdefMessage(createHandoverRequestRecord(), createBluetoothOobDataRecord());
    286     }
    287 
    288     NdefMessage createHandoverSelectMessage(boolean activating) {
    289         return new NdefMessage(createHandoverSelectRecord(activating), createBluetoothOobDataRecord());
    290     }
    291 
    292     NdefRecord createHandoverSelectRecord(boolean activating) {
    293         NdefMessage nestedMessage = new NdefMessage(createBluetoothAlternateCarrierRecord(activating));
    294         byte[] nestedPayload = nestedMessage.toByteArray();
    295 
    296         ByteBuffer payload = ByteBuffer.allocate(nestedPayload.length + 1);
    297         payload.put((byte)0x12);  // connection handover v1.2
    298         payload.put(nestedPayload);
    299 
    300         byte[] payloadBytes = new byte[payload.position()];
    301         payload.position(0);
    302         payload.get(payloadBytes);
    303         return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_HANDOVER_SELECT, null,
    304                 payloadBytes);
    305     }
    306 
    307     NdefRecord createHandoverRequestRecord() {
    308         NdefMessage nestedMessage = new NdefMessage(createCollisionRecord(),
    309                 createBluetoothAlternateCarrierRecord(false));
    310         byte[] nestedPayload = nestedMessage.toByteArray();
    311 
    312         ByteBuffer payload = ByteBuffer.allocate(nestedPayload.length + 1);
    313         payload.put((byte)0x12);  // connection handover v1.2
    314         payload.put(nestedMessage.toByteArray());
    315 
    316         byte[] payloadBytes = new byte[payload.position()];
    317         payload.position(0);
    318         payload.get(payloadBytes);
    319         return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_HANDOVER_REQUEST, null,
    320                 payloadBytes);
    321     }
    322 
    323     /**
    324      * Return null if message is not a Handover Request,
    325      * return the Handover Select response if it is.
    326      */
    327     public NdefMessage tryHandoverRequest(NdefMessage m) {
    328         if (m == null) return null;
    329         if (mBluetoothAdapter == null) return null;
    330 
    331         if (DBG) Log.d(TAG, "tryHandoverRequest():" + m.toString());
    332 
    333         NdefRecord r = m.getRecords()[0];
    334         if (r.getTnf() != NdefRecord.TNF_WELL_KNOWN) return null;
    335         if (!Arrays.equals(r.getType(), NdefRecord.RTD_HANDOVER_REQUEST)) return null;
    336 
    337         // we have a handover request, look for BT OOB record
    338         BluetoothHandoverData bluetoothData = null;
    339         for (NdefRecord oob : m.getRecords()) {
    340             if (oob.getTnf() == NdefRecord.TNF_MIME_MEDIA &&
    341                     Arrays.equals(oob.getType(), TYPE_BT_OOB)) {
    342                 bluetoothData = parseBtOob(ByteBuffer.wrap(oob.getPayload()));
    343                 break;
    344             }
    345         }
    346         if (bluetoothData == null) return null;
    347 
    348         // Note: there could be a race where we conclude
    349         // that Bluetooth is already enabled, and shortly
    350         // after the user turns it off. That will cause
    351         // the transfer to fail, but there's nothing
    352         // much we can do about it anyway. It shouldn't
    353         // be common for the user to be changing BT settings
    354         // while waiting to receive a picture.
    355         boolean bluetoothActivating = !mBluetoothAdapter.isEnabled();
    356         synchronized (mLock) {
    357             if (!mEnabled) return null;
    358 
    359             Message msg = Message.obtain(null, HandoverService.MSG_START_INCOMING_TRANSFER);
    360             PendingHandoverTransfer transfer = registerInTransferLocked(bluetoothData.device);
    361             Bundle transferData = new Bundle();
    362             transferData.putParcelable(HandoverService.BUNDLE_TRANSFER, transfer);
    363             msg.setData(transferData);
    364 
    365             if (!sendOrQueueMessageLocked(msg)) {
    366                 removeTransferLocked(transfer.id);
    367                 return null;
    368             }
    369         }
    370         // BT OOB found, whitelist it for incoming OPP data
    371         whitelistOppDevice(bluetoothData.device);
    372 
    373         // return BT OOB record so they can perform handover
    374         NdefMessage selectMessage = (createHandoverSelectMessage(bluetoothActivating));
    375         if (DBG) Log.d(TAG, "Waiting for incoming transfer, [" +
    376                 bluetoothData.device.getAddress() + "]->[" + mLocalBluetoothAddress + "]");
    377 
    378         return selectMessage;
    379     }
    380 
    381     public boolean sendOrQueueMessageLocked(Message msg) {
    382         if (!mBound || mService == null) {
    383             // Need to start service, let us know if we can queue the message
    384             if (!bindServiceIfNeededLocked()) {
    385                 Log.e(TAG, "Could not start service");
    386                 return false;
    387             }
    388             // Queue the message to send when the service is bound
    389             mPendingServiceMessages.add(msg);
    390         } else {
    391             try {
    392                 mService.send(msg);
    393             } catch (RemoteException e) {
    394                 Log.e(TAG, "Could not connect to handover service");
    395                 return false;
    396             }
    397         }
    398         return true;
    399     }
    400 
    401     public boolean tryHandover(NdefMessage m) {
    402         if (m == null) return false;
    403         if (mBluetoothAdapter == null) return false;
    404 
    405         if (DBG) Log.d(TAG, "tryHandover(): " + m.toString());
    406 
    407         BluetoothHandoverData handover = parse(m);
    408         if (handover == null) return false;
    409         if (!handover.valid) return true;
    410 
    411         synchronized (mLock) {
    412             if (!mEnabled) return false;
    413 
    414             if (mBluetoothAdapter == null) {
    415                 if (DBG) Log.d(TAG, "BT handover, but BT not available");
    416                 return true;
    417             }
    418 
    419             Message msg = Message.obtain(null, HandoverService.MSG_HEADSET_HANDOVER, 0, 0);
    420             Bundle headsetData = new Bundle();
    421             headsetData.putParcelable(HandoverService.EXTRA_HEADSET_DEVICE, handover.device);
    422             headsetData.putString(HandoverService.EXTRA_HEADSET_NAME, handover.name);
    423             msg.setData(headsetData);
    424             return sendOrQueueMessageLocked(msg);
    425         }
    426     }
    427 
    428     // This starts sending an Uri over BT
    429     public void doHandoverUri(Uri[] uris, NdefMessage m) {
    430         if (mBluetoothAdapter == null) return;
    431 
    432         BluetoothHandoverData data = parse(m);
    433         if (data != null && data.valid) {
    434             // Register a new handover transfer object
    435             synchronized (mLock) {
    436                 Message msg = Message.obtain(null, HandoverService.MSG_START_OUTGOING_TRANSFER, 0, 0);
    437                 PendingHandoverTransfer transfer = registerOutTransferLocked(data, uris);
    438                 Bundle transferData = new Bundle();
    439                 transferData.putParcelable(HandoverService.BUNDLE_TRANSFER, transfer);
    440                 msg.setData(transferData);
    441                 if (DBG) Log.d(TAG, "Initiating outgoing transfer, [" + mLocalBluetoothAddress +
    442                         "]->[" + data.device.getAddress() + "]");
    443                 sendOrQueueMessageLocked(msg);
    444             }
    445         }
    446     }
    447 
    448     PendingHandoverTransfer registerInTransferLocked(BluetoothDevice remoteDevice) {
    449         PendingHandoverTransfer transfer = new PendingHandoverTransfer(
    450                 mHandoverTransferId++, true, remoteDevice, false, null);
    451         mPendingTransfers.put(transfer.id, transfer);
    452 
    453         return transfer;
    454     }
    455 
    456     PendingHandoverTransfer registerOutTransferLocked(BluetoothHandoverData data,
    457             Uri[] uris) {
    458         PendingHandoverTransfer transfer = new PendingHandoverTransfer(
    459                 mHandoverTransferId++, false, data.device, data.carrierActivating, uris);
    460         mPendingTransfers.put(transfer.id, transfer);
    461         return transfer;
    462     }
    463 
    464     void removeTransferLocked(int id) {
    465         mPendingTransfers.remove(id);
    466     }
    467 
    468     void whitelistOppDevice(BluetoothDevice device) {
    469         if (DBG) Log.d(TAG, "Whitelisting " + device + " for BT OPP");
    470         Intent intent = new Intent(ACTION_WHITELIST_DEVICE);
    471         intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
    472         mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT);
    473     }
    474 
    475     boolean isCarrierActivating(NdefRecord handoverRec, byte[] carrierId) {
    476         byte[] payload = handoverRec.getPayload();
    477         if (payload == null || payload.length <= 1) return false;
    478         // Skip version
    479         byte[] payloadNdef = new byte[payload.length - 1];
    480         System.arraycopy(payload, 1, payloadNdef, 0, payload.length - 1);
    481         NdefMessage msg;
    482         try {
    483             msg = new NdefMessage(payloadNdef);
    484         } catch (FormatException e) {
    485             return false;
    486         }
    487 
    488         for (NdefRecord alt : msg.getRecords()) {
    489             byte[] acPayload = alt.getPayload();
    490             if (acPayload != null) {
    491                 ByteBuffer buf = ByteBuffer.wrap(acPayload);
    492                 int cps = buf.get() & 0x03; // Carrier Power State is in lower 2 bits
    493                 int carrierRefLength = buf.get() & 0xFF;
    494                 if (carrierRefLength != carrierId.length) return false;
    495 
    496                 byte[] carrierRefId = new byte[carrierRefLength];
    497                 buf.get(carrierRefId);
    498                 if (Arrays.equals(carrierRefId, carrierId)) {
    499                     // Found match, returning whether power state is activating
    500                     return (cps == CARRIER_POWER_STATE_ACTIVATING);
    501                 }
    502             }
    503         }
    504 
    505         return true;
    506     }
    507 
    508     BluetoothHandoverData parseHandoverSelect(NdefMessage m) {
    509         // TODO we could parse this a lot more strictly; right now
    510         // we just search for a BT OOB record, and try to cross-reference
    511         // the carrier state inside the 'hs' payload.
    512         for (NdefRecord oob : m.getRecords()) {
    513             if (oob.getTnf() == NdefRecord.TNF_MIME_MEDIA &&
    514                     Arrays.equals(oob.getType(), TYPE_BT_OOB)) {
    515                 BluetoothHandoverData data = parseBtOob(ByteBuffer.wrap(oob.getPayload()));
    516                 if (data != null && isCarrierActivating(m.getRecords()[0], oob.getId())) {
    517                     data.carrierActivating = true;
    518                 }
    519                 return data;
    520             }
    521         }
    522 
    523         return null;
    524     }
    525 
    526     BluetoothHandoverData parse(NdefMessage m) {
    527         NdefRecord r = m.getRecords()[0];
    528         short tnf = r.getTnf();
    529         byte[] type = r.getType();
    530 
    531         // Check for BT OOB record
    532         if (r.getTnf() == NdefRecord.TNF_MIME_MEDIA && Arrays.equals(r.getType(), TYPE_BT_OOB)) {
    533             return parseBtOob(ByteBuffer.wrap(r.getPayload()));
    534         }
    535 
    536         // Check for Handover Select, followed by a BT OOB record
    537         if (tnf == NdefRecord.TNF_WELL_KNOWN &&
    538                 Arrays.equals(type, NdefRecord.RTD_HANDOVER_SELECT)) {
    539             return parseHandoverSelect(m);
    540         }
    541 
    542         // Check for Nokia BT record, found on some Nokia BH-505 Headsets
    543         if (tnf == NdefRecord.TNF_EXTERNAL_TYPE && Arrays.equals(type, TYPE_NOKIA)) {
    544             return parseNokia(ByteBuffer.wrap(r.getPayload()));
    545         }
    546 
    547         return null;
    548     }
    549 
    550     BluetoothHandoverData parseNokia(ByteBuffer payload) {
    551         BluetoothHandoverData result = new BluetoothHandoverData();
    552         result.valid = false;
    553 
    554         try {
    555             payload.position(1);
    556             byte[] address = new byte[6];
    557             payload.get(address);
    558             result.device = mBluetoothAdapter.getRemoteDevice(address);
    559             result.valid = true;
    560             payload.position(14);
    561             int nameLength = payload.get();
    562             byte[] nameBytes = new byte[nameLength];
    563             payload.get(nameBytes);
    564             result.name = new String(nameBytes, Charset.forName("UTF-8"));
    565         } catch (IllegalArgumentException e) {
    566             Log.i(TAG, "nokia: invalid BT address");
    567         } catch (BufferUnderflowException e) {
    568             Log.i(TAG, "nokia: payload shorter than expected");
    569         }
    570         if (result.valid && result.name == null) result.name = "";
    571         return result;
    572     }
    573 
    574     BluetoothHandoverData parseBtOob(ByteBuffer payload) {
    575         BluetoothHandoverData result = new BluetoothHandoverData();
    576         result.valid = false;
    577 
    578         try {
    579             payload.position(2);
    580             byte[] address = new byte[6];
    581             payload.get(address);
    582             // ByteBuffer.order(LITTLE_ENDIAN) doesn't work for
    583             // ByteBuffer.get(byte[]), so manually swap order
    584             for (int i = 0; i < 3; i++) {
    585                 byte temp = address[i];
    586                 address[i] = address[5 - i];
    587                 address[5 - i] = temp;
    588             }
    589             result.device = mBluetoothAdapter.getRemoteDevice(address);
    590             result.valid = true;
    591 
    592             while (payload.remaining() > 0) {
    593                 byte[] nameBytes;
    594                 int len = payload.get();
    595                 int type = payload.get();
    596                 switch (type) {
    597                     case 0x08:  // short local name
    598                         nameBytes = new byte[len - 1];
    599                         payload.get(nameBytes);
    600                         result.name = new String(nameBytes, Charset.forName("UTF-8"));
    601                         break;
    602                     case 0x09:  // long local name
    603                         if (result.name != null) break;  // prefer short name
    604                         nameBytes = new byte[len - 1];
    605                         payload.get(nameBytes);
    606                         result.name = new String(nameBytes, Charset.forName("UTF-8"));
    607                         break;
    608                     default:
    609                         payload.position(payload.position() + len - 1);
    610                         break;
    611                 }
    612             }
    613         } catch (IllegalArgumentException e) {
    614             Log.i(TAG, "BT OOB: invalid BT address");
    615         } catch (BufferUnderflowException e) {
    616             Log.i(TAG, "BT OOB: payload shorter than expected");
    617         }
    618         if (result.valid && result.name == null) result.name = "";
    619         return result;
    620     }
    621 
    622     static byte[] addressToReverseBytes(String address) {
    623         String[] split = address.split(":");
    624         byte[] result = new byte[split.length];
    625 
    626         for (int i = 0; i < split.length; i++) {
    627             // need to parse as int because parseByte() expects a signed byte
    628             result[split.length - 1 - i] = (byte)Integer.parseInt(split[i], 16);
    629         }
    630 
    631         return result;
    632     }
    633 }
    634