Java android.bluetooth.BluetoothDevice 代码实例

・21 分钟阅读

以下是展示如何使用android.bluetooth.BluetoothDevice的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


/**
 * Connects to the GATT server hosted on the Bluetooth LE device.
 * 
 * @param address
 *            The device address of the destination device.
 * 
 * @return Return true if the connection is initiated successfully. The
 *         connection result is reported asynchronously through the
 *         {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
 *         callback.
 */
public boolean connect(final String address) {
        if (mBluetoothAdapter == null || address == null) {
                Log.w(TAG,
                                "BluetoothAdapter not initialized or unspecified address.");
                return false;
        }
        // Previously connected device. Try to reconnect.
        if (mBluetoothDeviceAddress != null
                        && address.equals(mBluetoothDeviceAddress)
                        && mBluetoothGatt != null) {
                Log.d(TAG,
                                "Trying to use an existing mBluetoothGatt for connection.");
                if (mBluetoothGatt.connect()) {
                        mConnectionState = STATE_CONNECTING;
                        return true;
                } else {
                        return false;
                }
        }
        final BluetoothDevice device = mBluetoothAdapter
                        .getRemoteDevice(address);
        if (device == null) {
                Log.w(TAG, "Device not found.  Unable to connect.");
                return false;
        }
        // We want to directly connect to the device, so we are setting the
        // autoConnect
        // parameter to false.
        mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
        Log.d(TAG, "Trying to create a new connection.");
        mBluetoothDeviceAddress = address;
        mConnectionState = STATE_CONNECTING;
        return true;
}
 

实例 2


public ConnectThread(BluetoothDevice device, boolean secure)
{
    mmDevice = device;
    BluetoothSocket tmp = null;
    mSocketType = secure ? "Secure" : "Insecure";
    // Get a BluetoothSocket for a connection with the
    // given BluetoothDevice
    try
    {
        if (secure)
        {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
        } else
        {
            tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
        }
    } catch (IOException e)
    {
        Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
    }
    mmSocket = tmp;
}
 

实例 3


@Override
public View getView( int position, View convertView, ViewGroup parent )
{
    final View row;
    final Holder holder;
    if( convertView == null )
    {
        row = LayoutInflater.from( getContext() ).inflate( android.R.layout.simple_list_item_1, parent, false );
        holder = new Holder();
        holder.DeviceNameTextView = (TextView) row.findViewById( android.R.id.text1 );
        row.setTag( holder );
    }
    else
    {
        row = convertView;
        holder = (Holder) row.getTag();
    }
    final BluetoothDevice device = getItem( position );
    final String deviceName = device.getName();
    if( deviceName == null )
    {
        holder.DeviceNameTextView.setText( "(Unnamed Device)" );
    }
    else
    {
        holder.DeviceNameTextView.setText( device.getName() );
    }
    return row;
}
 

实例 4


public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    final BluetoothDevice bondDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    if (mBluetoothGatt != null && mBluetoothGatt.getDevice() != null && bondDevice != null) {
        if (!bondDevice.getAddress().equals(mBluetoothGatt.getDevice().getAddress())) {
            Log.d(TAG, "Bond state wrong device");
            return; // That wasnt a device we care about!!
        }
    }
    if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
        final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
        if (state == BluetoothDevice.BOND_BONDED) {
            Log.d(TAG, "CALLBACK RECIEVED Bonded");
            authenticateConnection();
        } else if (state == BluetoothDevice.BOND_NONE) {
            Log.d(TAG, "CALLBACK RECIEVED: Not Bonded");
        } else if (state == BluetoothDevice.BOND_BONDING) {
            Log.d(TAG, "CALLBACK RECIEVED: Trying to bond");
        }
    }
}
 

实例 5


private void onRequestPairingConsent(String objectPath, int nativeData) {
    String address = checkPairingRequestAndGetAddress(objectPath, nativeData);
    if (address == null) return;
    /* The link key will not be stored if the incoming request has MITM
     * protection switched on. Unfortunately, some devices have MITM
     * switched on even though their capabilities are NoInputNoOutput,
     * so we may get this request many times. Also if we respond immediately,
     * the other end is unable to handle it. Delay sending the message.
     */
    if (mBluetoothService.getBondState().getBondState(address) == BluetoothDevice.BOND_BONDED) {
        Message message = mHandler.obtainMessage(EVENT_PAIRING_CONSENT_DELAYED_ACCEPT);
        message.obj = address;
        mHandler.sendMessageDelayed(message, 1500);
        return;
    }
    Intent intent = new Intent(BluetoothDevice.ACTION_PAIRING_REQUEST);
    intent.putExtra(BluetoothDevice.EXTRA_DEVICE, mAdapter.getRemoteDevice(address));
    intent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT,
                    BluetoothDevice.PAIRING_VARIANT_CONSENT);
    mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM);
    return;
}
 

实例 6


private View createView() {
    View view = getLayoutInflater().inflate(R.layout.bluetooth_pin_entry, null);
    String name = mLocalManager.getCachedDeviceManager().getName(mDevice);
    TextView messageView = (TextView) view.findViewById(R.id.message);
    mPairingView = (EditText) view.findViewById(R.id.text);
    mPairingView.addTextChangedListener(this);
    if (mType == BluetoothDevice.PAIRING_VARIANT_PIN) {
        messageView.setText(getString(R.string.bluetooth_enter_pin_msg, name));
        // Maximum of 16 characters in a PIN adb sync
        mPairingView.setFilters(new InputFilter[] {
                new LengthFilter(BLUETOOTH_PIN_MAX_LENGTH) });
    } else if (mType == BluetoothDevice.PAIRING_VARIANT_PASSKEY){
        messageView.setText(getString(R.string.bluetooth_enter_passkey_msg, name));
        // Maximum of 6 digits for passkey
        mPairingView.setInputType(InputType.TYPE_CLASS_NUMBER |
                InputType.TYPE_NUMBER_FLAG_SIGNED);
        mPairingView.setFilters(new InputFilter[] {
                new LengthFilter(BLUETOOTH_PASSKEY_MAX_LENGTH)});
    } else if (mType == BluetoothDevice.PAIRING_VARIANT_PASSKEY_CONFIRMATION) {
        mPairingView.setVisibility(View.GONE);
        messageView.setText(getString(R.string.bluetooth_confirm_passkey_msg, name,
                mPasskey));
    } else if (mType == BluetoothDevice.PAIRING_VARIANT_CONSENT) {
        mPairingView.setVisibility(View.GONE);
        messageView.setText(getString(R.string.bluetooth_incoming_pairing_msg, name));
    } else if (mType == BluetoothDevice.PAIRING_VARIANT_DISPLAY_PASSKEY) {
        mPairingView.setVisibility(View.GONE);
        messageView.setText(getString(R.string.bluetooth_display_passkey_msg, name, mPasskey));
    } else if (mType == BluetoothDevice.PAIRING_VARIANT_OOB_CONSENT) {
        mPairingView.setVisibility(View.GONE);
        messageView.setText(getString(R.string.bluetooth_incoming_pairing_msg, name));
    } else {
        Log.e(TAG, "Incorrect pairing type received, not creating view");
    }
    return view;
}
 

实例 7


public boolean connectHeadsetInternal(BluetoothDevice device) {
    synchronized (BluetoothHeadsetService.this) {
        BluetoothDevice currDevice = getCurrentDevice();
        if (currDevice == null) {
            BluetoothRemoteHeadset headset = new BluetoothRemoteHeadset();
            mRemoteHeadsets.put(device, headset);
            setState(device, BluetoothHeadset.STATE_CONNECTING);
            if (device.getUuids() == null) {
                // We might not have got the UUID change notification from
                // Bluez yet, if we have just paired. Try after 1.5 secs.
                Message msg = new Message();
                msg.what = CONNECT_HEADSET_DELAYED;
                msg.obj = device;
                mHandler.sendMessageDelayed(msg, 1500);
            } else {
                getSdpRecordsAndConnect(device);
            }
            return true;
        } else {
              Log.w(TAG, "connectHeadset(" + device + "): failed: already in state " +
                    mRemoteHeadsets.get(currDevice).mState +
                    " with headset " + currDevice);
        }
        return false;
    }
}
 

实例 8


private void onPair(String value) {
    if (mType == BluetoothDevice.PAIRING_VARIANT_PIN) {
        byte[] pinBytes = BluetoothDevice.convertPinToBytes(value);
        if (pinBytes == null) {
            return;
        }
        mDevice.setPin(pinBytes);
    } else if (mType == BluetoothDevice.PAIRING_VARIANT_PASSKEY) {
        int passkey = Integer.parseInt(value);
        mDevice.setPasskey(passkey);
    } else if (mType == BluetoothDevice.PAIRING_VARIANT_PASSKEY_CONFIRMATION) {
        mDevice.setPairingConfirmation(true);
    } else if (mType ==  BluetoothDevice.PAIRING_VARIANT_CONSENT) {
        mDevice.setPairingConfirmation(true);
    } else if (mType == BluetoothDevice.PAIRING_VARIANT_DISPLAY_PASSKEY) {
        // Do Nothing.
    } else if (mType == BluetoothDevice.PAIRING_VARIANT_OOB_CONSENT) {
        mDevice.setRemoteOutOfBandData();
    } else {
        Log.e(TAG, "Incorrect pairing type received");
    }
}
 

实例 9


@Override
public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        String name;
        if(action.equals(BluetoothDevice.ACTION_FOUND)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                BluetoothClass btClass = intent.getParcelableExtra(BluetoothDevice.EXTRA_CLASS);
                name = device.getName() +"n" + device.getAddress() + 
                           ":" + btClass.getDeviceClass();
                if(mDeviceData.get(0).equals("No Devices"))
                        mDeviceData.clear();
                if(!mDeviceData.contains(name)) {
                        mDeviceData.add(name);
                        mMessageView.setText("Found " + mDeviceData.size() + " devices");
                        mDelegate.notifyDataSetChanged();
                } else {
                        mMessageView.setText("Found " + mDeviceData.size() + " devices");
                }
        }
}
 

实例 10


/**
 * Handle the pairing or the unpairing of a supported devices at runtime
 *
 * @param context The context provided by the OS
 * @param intent The Intent received from the OS
 */
@Override
public void onReceive(Context context, Intent intent) {
    if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(intent.getAction())) {
        // Retrieve the bond state and the device involved
        int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
        BluetoothDevice dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        // If the device has been paired...
        if (bondState == BluetoothDevice.BOND_BONDED) {
            // ...check whether is supported and add it to the list
            if (isSupportedDevice(dev.getAddress())) {
                pairedDevices.add(dev.getAddress());
            }
        }
        // If the device has been unpaired...
        else if (bondState == BluetoothDevice.BOND_NONE) {
            // ...remove it from the list
            if (pairedDevices.contains(dev.getAddress())) {
                pairedDevices.remove(dev.getAddress());
            }
        }
    }
}
 

实例 11


public ConnectThread(BluetoothDevice device) {
        mmDevice = device;
        BluetoothSocket tmp = null;
        // Get a BluetoothSocket for a connection with the
        // given BluetoothDevice
        try {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
                Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
        }
        mmSocket = tmp;
}
 

实例 12


/**
 * Returns the user-friendly name of a remote device.  This value is
 * retrned from our local cache, which is updated during device discovery.
 * Do not expect to retrieve the updated remote name immediately after
 * changing the name on the remote device.
 *
 * @param address Bluetooth address of remote device.
 *
 * @return The user-friendly name of the specified remote device.
 */
public synchronized String getRemoteName(String address) {
    mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
    if (!BluetoothDevice.checkBluetoothAddress(address)) {
        return null;
    }
    return getRemoteNameNative(address);
}
 

实例 13


public boolean canBluetooth() {
        // Detect if any bluetooth a device is available for call
        if (bluetoothAdapter == null) {
            // Device does not support Bluetooth
                return false;
        }
        boolean hasConnectedDevice = false;
        //If bluetooth is on
        if(bluetoothAdapter.isEnabled()) {
                //We get all bounded bluetooth devices
                // bounded is not enough, should search for connected devices....
                Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
                for(BluetoothDevice device : pairedDevices) {
                        BluetoothClass bluetoothClass = device.getBluetoothClass();
               if (bluetoothClass != null) {
                int deviceClass = bluetoothClass.getDeviceClass();
                if(bluetoothClass.hasService(Service.RENDER) ||
                        deviceClass == Device.AUDIO_VIDEO_WEARABLE_HEADSET ||
                        deviceClass == Device.AUDIO_VIDEO_CAR_AUDIO ||
                        deviceClass == Device.AUDIO_VIDEO_HANDSFREE ) {
                        //And if any can be used as a audio handset
                        hasConnectedDevice = true;
                        break;
                }
                        }
                }
        }
        boolean retVal = hasConnectedDevice && audioManager.isBluetoothScoAvailableOffCall();
        Log.d(THIS_FILE, "Can I do BT ? "+retVal);
        return retVal;
}
 

实例 14


@Override
 public void onCreate() {
     super.onCreate();
     mAdapter = BluetoothAdapter.getDefaultAdapter();
     mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
     mBtHandsfree = PhoneApp.getInstance().getBluetoothHandsfree();
     mAg = new BluetoothAudioGateway(mAdapter);
     IntentFilter filter = new IntentFilter(
             BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
     filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
     filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
     filter.addAction(AudioManager.VOLUME_CHANGED_ACTION);
     filter.addAction(BluetoothDevice.ACTION_UUID);
     registerReceiver(mBluetoothReceiver, filter);
     IBinder b = ServiceManager.getService(BluetoothAdapter.BLUETOOTH_SERVICE);
     if (b == null) {
         throw new RuntimeException("Bluetooth service not available");
     }
     mBluetoothService = IBluetooth.Stub.asInterface(b);
     mRemoteHeadsets = new HashMap<BluetoothDevice, BluetoothRemoteHeadset>();
}
 

实例 15


private void onCreateBondingResult(String address, int result) {
    address = address.toUpperCase();
    if (result == BluetoothError.SUCCESS) {
        mBluetoothService.getBondState().setBondState(address, BluetoothDevice.BOND_BONDED);
        if (mBluetoothService.getBondState().isAutoPairingAttemptsInProgress(address)) {
            mBluetoothService.getBondState().clearPinAttempts(address);
        }
    } else if (result == BluetoothDevice.UNBOND_REASON_AUTH_FAILED &&
            mBluetoothService.getBondState().getAttempt(address) == 1) {
        mBluetoothService.getBondState().addAutoPairingFailure(address);
        pairingAttempt(address, result);
    } else if (result == BluetoothDevice.UNBOND_REASON_REMOTE_DEVICE_DOWN &&
            mBluetoothService.getBondState().isAutoPairingAttemptsInProgress(address)) {
        pairingAttempt(address, result);
    } else {
        mBluetoothService.getBondState().setBondState(address,
                                                      BluetoothDevice.BOND_NOT_BONDED, result);
        if (mBluetoothService.getBondState().isAutoPairingAttemptsInProgress(address)) {
            mBluetoothService.getBondState().clearPinAttempts(address);
        }
    }
}
 
讨论
淘淘あ西西 profile image