Java Code Examples for android.bluetooth.BluetoothDevice#getBondState()

The following examples show how to use android.bluetooth.BluetoothDevice#getBondState() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InPenService.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.KITKAT)
private void bondAsRequired(final boolean wait) {
    final BluetoothDevice device = I.bleDevice.getBluetoothDevice();
    final int bondState = device.getBondState();
    if (bondState == BOND_NONE) {
        final boolean bondResultCode = device.createBond();
        UserError.Log.d(TAG, "Attempted create bond: result: " + bondResultCode);
    } else {
        UserError.Log.d(TAG, "Device is already in bonding state: " + Helper.bondStateToString(bondState));
    }

    if (wait) {
        for (int c = 0; c < 10; c++) {
            if (device.getBondState() == BOND_BONDED) {
                UserError.Log.d(TAG, "Bond created!");
                changeNextState();
                break;
            } else {
                UserError.Log.d(TAG, "Sleeping waiting for bond: " + c);
                JoH.threadSleep(1000);
            }
        }
    }
}
 
Example 2
Source File: DeviceListActivity.java    From grblcontroller with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
            mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
        setProgressBarIndeterminateVisibility(false);
        setTitle(getString(R.string.text_select_paired_device));
        if (mNewDevicesArrayAdapter.getCount() == 0) {
            mNewDevicesArrayAdapter.add(getString(R.string.text_none_found));
        }
    }
}
 
Example 3
Source File: ChooseDeviceActivity.java    From nxt-remote-control with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    
    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        if ((device.getBondState() != BluetoothDevice.BOND_BONDED) && (device.getBluetoothClass().getDeviceClass() == BluetoothClass.Device.TOY_ROBOT)) {
            mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
            findViewById(R.id.no_devices).setVisibility(View.GONE);
        }
    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
        setProgressBarIndeterminateVisibility(false);
        setTitle("Select device");
        findViewById(R.id.button_scan).setVisibility(View.VISIBLE);
    }
}
 
Example 4
Source File: DeviceListActivity.java    From retroband with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    // When discovery finds a device
    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        // Get the BluetoothDevice object from the Intent
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        // If it's already paired, skip it, because it's been listed already
        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
            mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
    // When discovery is finished, change the Activity title
    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
        setProgressBarIndeterminateVisibility(false);
        setTitle(R.string.select_device);
        if (mNewDevicesArrayAdapter.getCount() == 0) {
            String noDevices = getResources().getText(R.string.none_found).toString();
            mNewDevicesArrayAdapter.add(noDevices);
        }
        mScanButton.setVisibility(View.VISIBLE);
    }
}
 
Example 5
Source File: BCLServiceClient.java    From unity-bluetooth with MIT License 6 votes vote down vote up
private BroadcastReceiver createBroadcastReceiver(final String pairingAddress) {
    return new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    if (pairingAddress.equals(device.getAddress())) {
                        mConnectThread = new ConnectThread(device);
                        mConnectThread.start();
                        for (BCLServiceListener listener : listeners) {
                            listener.onDeviceConnect(true);
                        }
                    }
                }
            }
        }
    };
}
 
Example 6
Source File: DeviceListActivity.java    From retrowatch with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    // When discovery finds a device
    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        // Get the BluetoothDevice object from the Intent
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        // If it's already paired, skip it, because it's been listed already
        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
            mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
    // When discovery is finished, change the Activity title
    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
        setProgressBarIndeterminateVisibility(false);
        setTitle(R.string.select_device);
        if (mNewDevicesArrayAdapter.getCount() == 0) {
            String noDevices = getResources().getText(R.string.none_found).toString();
            mNewDevicesArrayAdapter.add(noDevices);
        }
        mScanButton.setVisibility(View.VISIBLE);
    }
}
 
Example 7
Source File: DeviceListActivity.java    From retrowatch with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    // When discovery finds a device
    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        // Get the BluetoothDevice object from the Intent
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        // If it's already paired, skip it, because it's been listed already
        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
            mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
    // When discovery is finished, change the Activity title
    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
        setProgressBarIndeterminateVisibility(false);
        setTitle(R.string.select_device);
        if (mNewDevicesArrayAdapter.getCount() == 0) {
            String noDevices = getResources().getText(R.string.none_found).toString();
            mNewDevicesArrayAdapter.add(noDevices);
        }
        mScanButton.setVisibility(View.VISIBLE);
    }
}
 
Example 8
Source File: Bluetooth.java    From Makeblock-App-For-Android with MIT License 5 votes vote down vote up
public List<String> getBtDevList(){
         
        List<String> data = new ArrayList<String>();
        Set<BluetoothDevice> pairedDevices = mBTAdapter.getBondedDevices();
//      prDevices.clear();
		if (pairedDevices.size() > 0) {
          for (BluetoothDevice device : pairedDevices) {
          	if(!btDevices.contains(device))
          	btDevices.add(device);
          }
      }
        for(BluetoothDevice dev : btDevices){
        	String s = dev.getName();
        	if(s!=null){
	        	if(s.indexOf("null")>-1){
	        		s = "Bluetooth";
	        	}
        	}else{
        		s = "Bluetooth";
        	}
        	//String[] a = dev.getAddress().split(":");
        	s=s+" "+dev.getAddress()+" "+(dev.getBondState()==BluetoothDevice.BOND_BONDED?((connDev!=null && connDev.equals(dev))?getString(R.string.connected):getString(R.string.bonded)):getString(R.string.unbond));
        	
        	data.add(s);
        }
      
//        for(BluetoothDevice dev : prDevices){
//        	String s = dev.getName();
//        	s=s+" "+dev.getAddress();
//        	if(connDev!=null && connDev.equals(dev)){
//        		s="-> "+s;
//        	}
//        	data.add(s);
//        }
        return data;
    }
 
Example 9
Source File: DevicesAdapter.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private String getState(final BluetoothDevice device, final int position) {
	if (connectingPosition == position)
		return connectingText;
	else if (device.getBondState() == BluetoothDevice.BOND_BONDED)
		return bondedText;
	else if (device.getBondState() == BluetoothDevice.BOND_BONDING)
		return bondingText;
	return availableText;
}
 
Example 10
Source File: Nes30Connection.java    From android-robocar with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void onReceive(Context context, Intent intent) {
  String action = intent.getAction();
  // Discovery has found a device.
  if (BluetoothDevice.ACTION_FOUND.equals(action)) {
    // Get the BluetoothDevice object and its info from the Intent.
    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    int bondState = device.getBondState();
    String foundName = device.getName();
    String foundAddress = device.getAddress(); // MAC address
    Timber.d("Discovery has found a device: %d/%s/%s", bondState, foundName, foundAddress);
    if (isSelectedDevice(foundAddress)) {
      createBond(device);
    } else {
      Timber.d("Unknown device, skipping bond attempt.");
    }
  } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
    int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
    switch (state) {
      case BluetoothDevice.BOND_NONE:
        Timber.d("The remote device is not bonded.");
        break;
      case BluetoothDevice.BOND_BONDING:
        Timber.d("Bonding is in progress with the remote device.");
        break;
      case BluetoothDevice.BOND_BONDED:
        Timber.d("The remote device is bonded.");
        break;
      default:
        Timber.d("Unknown remote device bonding state.");
        break;
    }
  }
}
 
Example 11
Source File: Bluetooth.java    From android-tv-launcher with MIT License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    String action = intent.getAction();
    BluetoothDevice device = null;
    device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    if(device!=null){
    }
    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        if (device.getBondState() == BluetoothDevice.BOND_NONE) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("name", device.getName());
            map.put("type", device.getBluetoothClass().getDeviceClass());
            map.put("device", device);
            if (list.indexOf(map) == -1) {// 防止重复添加
                list.add(map);
                itemAdapter = new MyBluetoothAdapter(context, list);
                searchDeviceLV.setAdapter(itemAdapter);
            }
        }
    } else if (device != null && device.getBondState() == BluetoothDevice.BOND_BONDING) {
        showShortToast("正在配对");
    } else if (device != null && device.getBondState() == BluetoothDevice.BOND_BONDED) {
        pairTVName.setText(device.getName());
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).get("device").equals(device)) {
                pairPosition = i;
                list.remove(i);
                itemAdapter.notifyDataSetChanged();
            }
        }
        showShortToast("配对完成");
    }
}
 
Example 12
Source File: SearchPrinterDialog.java    From esc-pos-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
  String action = intent.getAction();

  if (BluetoothDevice.ACTION_FOUND.equals(action) || BluetoothDevice.ACTION_CLASS_CHANGED.equals(action) || BluetoothDevice.ACTION_NAME_CHANGED.equals(action)) {
    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
      View view = makeItem(device);
      if (view != null) availableDevicesContainer.addView(view);
    }
  } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
    service.setState(BTService.STATE_NONE);
    progress.setVisibility(View.GONE);
  }
}
 
Example 13
Source File: EasyBLE.java    From easyble-x with Apache License 2.0 5 votes vote down vote up
/**
 * 创建连接
 *
 * @param device        蓝牙设备实例
 * @param configuration 连接配置
 * @param observer      伴生观察者
 * @return 返回创建的连接实例,创建失败则返回null
 */
@Nullable
public synchronized Connection connect(@NonNull final Device device, @Nullable ConnectionConfiguration configuration,
                                       @Nullable final EventObserver observer) {
    if (checkStatus()) {
        Inspector.requireNonNull(device, "device can't be null");
        Connection connection = connectionMap.remove(device.getAddress());
        //如果连接已存在,先释放掉
        if (connection != null) {
            connection.releaseNoEvent();
        }
        Boolean isConnectable = device.isConnectable();
        if (isConnectable == null || isConnectable) {
            int connectDelay = 0;
            if (bondController != null && bondController.accept(device)) {
                BluetoothDevice remoteDevice = bluetoothAdapter.getRemoteDevice(device.getAddress());
                if (remoteDevice.getBondState() != BluetoothDevice.BOND_BONDED) {
                    connectDelay = createBond(device.getAddress()) ? 1500 : 0;
                }
            }
            connection = new ConnectionImpl(this, bluetoothAdapter, device, configuration, connectDelay, observer);
            connectionMap.put(device.address, connection);
            addressList.add(device.address);
            return connection;
        } else {
            String message = String.format(Locale.US, "connect failed! [type: unconnectable, name: %s, addr: %s]",
                    device.getName(), device.getAddress());
            logger.log(Log.ERROR, Logger.TYPE_CONNECTION_STATE, message);
            if (observer != null) {
                posterDispatcher.post(observer, MethodInfoGenerator.onConnectFailed(device, Connection.CONNECT_FAIL_TYPE_CONNECTION_IS_UNSUPPORTED));
            }
            observable.notifyObservers(MethodInfoGenerator.onConnectFailed(device, Connection.CONNECT_FAIL_TYPE_CONNECTION_IS_UNSUPPORTED));
        }
    }
    return null;
}
 
Example 14
Source File: AbstractHOGPServer.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
@Override
public void onConnectionStateChange(final BluetoothDevice device, final int status, final int newState) {
    if (DEBUG) {
        Log.d(TAG, "onConnectionStateChange status: " + status + ", newState: " + newState);
    }

    if (mGattServer == null) {
        return;
    }

    switch (newState) {
        case BluetoothProfile.STATE_CONNECTED:
            if (DEBUG) {
                Log.d(TAG, "BluetoothProfile.STATE_CONNECTED bondState: " + device.getBondState());
            }

            // check bond status
            if (device.getBondState() == BluetoothDevice.BOND_NONE) {
                paringDevice(device);
            } else if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                connectDevice(device);
            }
            break;

        case BluetoothProfile.STATE_DISCONNECTED:
            if (DEBUG) {
                Log.w(TAG, "BluetoothProfile.STATE_DISCONNECTED");
            }
            disconnectDevice(device);
            break;

        default:
            // do nothing
            break;
    }
}
 
Example 15
Source File: BluetoothActivity.java    From Android-Bluetooth-Fingerprint with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent)
{
    String action = intent.getAction();

    // When discovery finds a device
    if (BluetoothDevice.ACTION_FOUND.equals(action))
    {
        // Get the BluetoothDevice object from the Intent
        BluetoothDevice device = intent
                .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        // If it's already paired, skip it, because it's been listed
        // already
        if (device.getBondState() != BluetoothDevice.BOND_BONDED)
        {
            mNewDevicesArrayAdapter.add(device.getName() + "\n"
                    + device.getAddress());
        }
        // When discovery is finished, change the Activity title
    }
    else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
    {
        setProgressBarIndeterminateVisibility(false);
        setTitle(R.string.select_device);
        if (mNewDevicesArrayAdapter.getCount() == 0)
        {
            String noDevices = getResources().getText(
                    R.string.none_found).toString();
            mNewDevicesArrayAdapter.add(noDevices);
        }
    }
}
 
Example 16
Source File: BluetoothWrapper.java    From phonegap-bluetooth-plugin with MIT License 5 votes vote down vote up
/**
 * Check if the device at given address is bonded with this device.
 *
 * @param address The device we want to check against.
 * @return Flag indicating whether the devices are bonded.
 * @throws Exception If there is a problem deducing the bond state. A wrong address might also cause this. :)
 *
 * @see BluetoothDevice
 */
public boolean isBonded(String address) throws Exception
{
	try
	{
		BluetoothDevice device = _adapter.getRemoteDevice(address);
		return device.getBondState() == BluetoothDevice.BOND_BONDED;
	}
	catch(Exception e)
	{
		throw e;
	}
}
 
Example 17
Source File: BluetoothConnectionHelper.java    From DataLogger with MIT License 4 votes vote down vote up
/**
 * Start the ConnectThread to initiate a connection to a remote device.
 *
 * @param address The address to connect
 */
public synchronized void connect(String address, int index) {
    Log.i(TAG, "::connect Trying to connect to address " + address + ". ");

    // Cancel any thread attempting to make a connection
    if (mStates[index] == STATE_CONNECTING) {
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }
    }

    // Cancel any thread currently running a connection
    if (mConnectedThreads[index] != null) {
        mConnectedThreads[index].cancel();
        mConnectedThreads[index] = null;
    }

    // Get the BluetoothDevice object
    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    switch (device.getBondState()){
        case BluetoothDevice.BOND_NONE:
            Log.i(TAG, "The remote device is not bonded (paired)");
            break;
        case BluetoothDevice.BOND_BONDING:
            Log.i(TAG, "Bonding (pairing) is in progress with the remote device");
            break;
        case BluetoothDevice.BOND_BONDED:
            Log.i(TAG, "The remote device is bonded (paired)");
            boolean remoteUuid = false;
            for (ParcelUuid uuid : device.getUuids()){
                if (mUUIDs[index].equals(uuid.toString())) {
                    remoteUuid = true;
                }
                Log.i(TAG, "::connect "+ uuid.toString() + ". Is target uuid: " + mUUIDs[index].equals(uuid.toString()));
            }
            if (!remoteUuid) {
                Log.e(TAG, "::connect Service UUID (" + mUUIDs[index] + ") not supported in remote device.");
            }
            break;
    }

    // Start the thread to connect with the given device
    mConnectThread = new ConnectThread(device, index);
    mConnectThread.start();
    setState(STATE_CONNECTING, index);

}
 
Example 18
Source File: GilgaService.java    From gilgamesh with GNU General Public License v3.0 4 votes vote down vote up
private void sendDirectMessage (String message)
{
	
	StringTokenizer st = new StringTokenizer(message," ");
	String cmd = st.nextToken();
	String address = st.nextToken();
	
	if (address.equals(mLocalShortBluetoothAddress)
			|| address.equals(mBluetoothAdapter.getAddress()))
			{
		//can't send DM's to yourself
		Toast.makeText(this, R.string.you_can_t_send_private_messages_to_yourself, Toast.LENGTH_SHORT).show();
		return;
			}
	
	try
	{
 	final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
 	final boolean isSecure = device.getBondState()==BluetoothDevice.BOND_BONDED;
 	
 	StringBuffer dMessage = new StringBuffer();
 	
 	while (st.hasMoreTokens())
 		dMessage.append(st.nextToken()).append(" ");
 	
 	DirectMessage dm = new DirectMessage();
 	dm.to = address;
 	dm.body = dMessage.toString().trim();
 	dm.ts = new java.util.Date().getTime();
 	dm.delivered = false;
	
 	mQueuedDirectMessage.add(dm);
 	
 	dm.trusted = isSecure;
 	GilgaApp.mStatusAdapter.add(dm);
 	
 	if (mDirectChatSession == null)
 	{
 	 mDirectChatSession = new DirectMessageSession(this, mHandler);
   	 mDirectChatSession.start();
 	}
 	else
 	{
 		mDirectChatSession.disconnect();
 	}
 	
 	mHandler.postAtTime(new Runnable ()
 	{
 		public void run ()
 		{
 	    	mDirectChatSession.connect(device, isSecure);
 		}
 	}, 2000);
	}
	catch (IllegalArgumentException iae)
	{
		Toast.makeText(this, getString(R.string.error_sending_message_) + iae.getLocalizedMessage(), Toast.LENGTH_LONG).show();
	}
	
}
 
Example 19
Source File: BtReceiver.java    From EasyBluetoothFrame with Apache License 2.0 4 votes vote down vote up
@Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // Get the BluetoothDevice object from the Intent
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Add the name and address to an array adapter to show in a ListView
            if (scanResultListener != null) {
                scanResultListener.onDeviceFound(device);
            }
            //配对请求
        } else if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {
//            try {
//
//                //1.确认配对
//                Method setPairingConfirmation = device.getClass().getDeclaredMethod("setPairingConfirmation", boolean.class);
//                setPairingConfirmation.invoke(device, true);
//                //2.终止有序广播
//                abortBroadcast();//如果没有将广播终止,则会出现一个一闪而过的配对框。
//                //3.调用setPin方法进行配对...
////                boolean ret = ClsUtils.setPin(device.getClass(), device, pin);
//                Method removeBondMethod = device.getClass().getDeclaredMethod("setPin", new Class[]{byte[].class});
//                Boolean returnValue = (Boolean) removeBondMethod.invoke(device, new Object[]{pin.getBytes()});
//            } catch (Exception e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//                if (pinResultListener != null) {
//                    pinResultListener.pairFailed(device);
//                }
//
//            }
        } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
            switch (device.getBondState()) {
                case BluetoothDevice.BOND_NONE:
                    Log.d(TAG, "取消配对");
                    if (pinResultListener != null)
                        pinResultListener.pairFailed(device);
                    break;
                case BluetoothDevice.BOND_BONDING:
                    Log.d(TAG, "配对中");
                    if (pinResultListener != null)
                        pinResultListener.pairing(device);
                    break;
                case BluetoothDevice.BOND_BONDED:
                    Log.d(TAG, "配对成功");
                    if (pinResultListener != null)
                        pinResultListener.paired(device);
                    break;

            }
        }else if ((BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)&&intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)
                == BluetoothAdapter.STATE_OFF)||BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)){

                if(serverConnectResultListener!=null)
                    serverConnectResultListener.disconnected();
                if(clientConnectResultListener!=null)
                    clientConnectResultListener.disconnected();


        }

    }
 
Example 20
Source File: BluetoothEventManager.java    From talkback with Apache License 2.0 4 votes vote down vote up
@RequiresPermission(allOf = {permission.BLUETOOTH, permission.BLUETOOTH_ADMIN})
@Override
public void onReceive(Context context, Intent intent) {
  String action = intent.getAction();
  BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  if (bluetoothDevice == null) {
    return;
  }
  ComparableBluetoothDevice comparableBluetoothDevice =
      new ComparableBluetoothDevice(
          context, bluetoothAdapter, bluetoothDevice, bluetoothDeviceActionListener);
  if (BluetoothDevice.ACTION_NAME_CHANGED.equals(action)
      || BluetoothDevice.ACTION_FOUND.equals(action)) {
    String bluetoothDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
    comparableBluetoothDevice.setName(bluetoothDeviceName);
    if (action.equals(BluetoothDevice.ACTION_FOUND)) {
      BluetoothClass bluetoothDeviceClass =
          intent.getParcelableExtra(BluetoothDevice.EXTRA_CLASS);
      comparableBluetoothDevice.setBluetoothClass(bluetoothDeviceClass);
    }

    /* Don't add a device if it's already been bonded (paired) to the device. */
    if (bluetoothDevice.getBondState() != BluetoothDevice.BOND_BONDED) {
      short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);
      comparableBluetoothDevice.setRssi(rssi);
      dispatchDeviceDiscoveredEvent(comparableBluetoothDevice);
      // TODO: Remove available devices from adapter if they become
      // unavailable. This will most likely be unable to be addressed without API changes.
    } else {
      dispatchDevicePairedEvent(comparableBluetoothDevice);
    }
  } else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
    if (bluetoothDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
      comparableBluetoothDevice.setConnectionState(BluetoothConnectionState.CONNECTED);
      dispatchDeviceConnectionStateChangedEvent(comparableBluetoothDevice);
    }
  } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
    if (bluetoothDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
      comparableBluetoothDevice.setConnectionState(BluetoothConnectionState.UNKNOWN);
      dispatchDeviceConnectionStateChangedEvent(comparableBluetoothDevice);
    }
  } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
    if (bluetoothDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
      comparableBluetoothDevice.setConnectionState(BluetoothConnectionState.CONNECTED);
      dispatchDevicePairedEvent(comparableBluetoothDevice);
    } else if (bluetoothDevice.getBondState() == BluetoothDevice.BOND_NONE) {
      /* The call to #createBond has completed, but the Bluetooth device isn't bonded, so
       * set the connection state to unavailable. */
      comparableBluetoothDevice.setConnectionState(BluetoothConnectionState.UNAVAILABLE);
      dispatchDeviceConnectionStateChangedEvent(comparableBluetoothDevice);
    }

    /* If we canceled discovery before beginning the pairing process, resume discovery after
     * {@link BluetoothDevice#createBond} finishes. */
    if (bluetoothDevice.getBondState() != BluetoothDevice.BOND_BONDING
        && !bluetoothAdapter.isDiscovering()) {
      bluetoothAdapter.startDiscovery();
    }
  }
}