Java Code Examples for android.bluetooth.BluetoothAdapter#getBondedDevices()

The following examples show how to use android.bluetooth.BluetoothAdapter#getBondedDevices() . 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: AppRTCBluetoothManager.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Logs the state of the local Bluetooth adapter.
 */
@SuppressLint("HardwareIds")
protected void logBluetoothAdapterInfo(BluetoothAdapter localAdapter) {
    Log.d(Config.LOGTAG, "BluetoothAdapter: "
            + "enabled=" + localAdapter.isEnabled() + ", "
            + "state=" + stateToString(localAdapter.getState()) + ", "
            + "name=" + localAdapter.getName() + ", "
            + "address=" + localAdapter.getAddress());
    // Log the set of BluetoothDevice objects that are bonded (paired) to the local adapter.
    Set<BluetoothDevice> pairedDevices = localAdapter.getBondedDevices();
    if (!pairedDevices.isEmpty()) {
        Log.d(Config.LOGTAG, "paired devices:");
        for (BluetoothDevice device : pairedDevices) {
            Log.d(Config.LOGTAG, " name=" + device.getName() + ", address=" + device.getAddress());
        }
    }
}
 
Example 2
Source File: MainActivity.java    From rpi3-wifi-conf-android with MIT License 6 votes vote down vote up
private void refreshDevices() {
    adapter_devices = new DeviceAdapter(this, R.layout.spinner_devices, new ArrayList<BluetoothDevice>());
    devicesSpinner.setAdapter(adapter_devices);

    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBluetooth, 0);
    }

    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    if (pairedDevices.size() > 0) {
        for (BluetoothDevice device : pairedDevices) {
            adapter_devices.add(device);
        }
    }
}
 
Example 3
Source File: Miband.java    From Mi_Band_SDK with Apache License 2.0 6 votes vote down vote up
/**
 * Miband 디바이스 찾기, Mi fit 앱에서 먼저 bonded 된 Device를 찾는다.
 *
 * @param mBluetoothAdapter
 * @param callback
 */
public void searchDevice(final BluetoothAdapter mBluetoothAdapter, final MibandCallback callback) {
    this.mibandIO.setStatus(MibandCallback.STATUS_SEARCH_DEVICE);
    Set<BluetoothDevice> pairDevices = mBluetoothAdapter.getBondedDevices();
    BluetoothDevice mibandDevice = null;
    if (pairDevices.size() > 0) {
        for (BluetoothDevice device : pairDevices) {
            String deviceMac = device.getAddress().substring(0, 8);
            if (MibandUUID.MAC_FILTER_MI1S.equals(deviceMac)) {
                mibandDevice = device;
                break;
            }
        }
    }
    if (mibandDevice == null)
        callback.onFail(-1, "실패", MibandCallback.STATUS_SEARCH_DEVICE);
    else
        callback.onSuccess(mibandDevice, MibandCallback.STATUS_SEARCH_DEVICE);
}
 
Example 4
Source File: BluetoothUtils.java    From microbit with Apache License 2.0 6 votes vote down vote up
public static BluetoothDevice getPairedDeviceMicroBit(Context context) {
    SharedPreferences pairedDevicePref = context.getApplicationContext().getSharedPreferences(PREFERENCES_KEY,
            Context.MODE_MULTI_PROCESS);
    if(pairedDevicePref.contains(PREFERENCES_PAIREDDEV_KEY)) {
        String pairedDeviceString = pairedDevicePref.getString(PREFERENCES_PAIREDDEV_KEY, null);
        Gson gson = new Gson();
        sConnectedDevice = gson.fromJson(pairedDeviceString, ConnectedDevice.class);
        //Check if the microbit is still paired with our mobile
        BluetoothAdapter mBluetoothAdapter = ((BluetoothManager) MBApp.getApp().getSystemService(Context
                .BLUETOOTH_SERVICE)).getAdapter();
        if(mBluetoothAdapter.isEnabled()) {
            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
            for(BluetoothDevice bt : pairedDevices) {
                if(bt.getAddress().equals(sConnectedDevice.mAddress)) {
                    return bt;
                }
            }
        }
    }
    return null;
}
 
Example 5
Source File: PairingActivity.java    From microbit with Apache License 2.0 6 votes vote down vote up
/**
 * Finds all bonded devices and tries to unbond it.
 */
private void unPairDevice() {
    ConnectedDevice connectedDevice = BluetoothUtils.getPairedMicrobit(this);
    String addressToDelete = connectedDevice.mAddress;
    // Get the paired devices and put them in a Set
    BluetoothAdapter mBluetoothAdapter = ((BluetoothManager) getSystemService(BLUETOOTH_SERVICE)).getAdapter();
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    for(BluetoothDevice bt : pairedDevices) {
        logi("Paired device " + bt.getName());
        if(bt.getAddress().equals(addressToDelete)) {
            try {
                Method m = bt.getClass().getMethod("removeBond", (Class[]) null);
                m.invoke(bt, (Object[]) null);
            } catch(NoSuchMethodException | IllegalAccessException
                    | InvocationTargetException e) {
                Log.e(TAG, e.toString());
            }
        }
    }
}
 
Example 6
Source File: SdlRouterService.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
    * This function looks through the phones currently paired bluetooth devices
    * If one of the devices' names contain "sync", or livio it will attempt to connect the RFCOMM
    * And start SDL
    * @return a boolean if a connection was attempted
    */
 @SuppressWarnings({"MissingPermission", "unused"})
public synchronized boolean bluetoothQuerryAndConnect(){
	BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
	if(adapter != null && adapter.isEnabled()){
		Set<BluetoothDevice> pairedBT= adapter.getBondedDevices();
       	Log.d(TAG, "Query Bluetooth paired devices");
       	if (pairedBT.size() > 0) {
           	for (BluetoothDevice device : pairedBT) {
           		String name = device.getName().toLowerCase(Locale.US);
           		if(name.contains("sync") || name.contains("livio")){
           			bluetoothConnect(device);
					return true;
               	}
           	}
      		}
	}else{
		Log.e(TAG, "There was an issue with connecting as client");
	}
	 return false;
 }
 
Example 7
Source File: AbstractDanaRExecutionService.java    From AndroidAPS with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void getBTSocketForSelectedPump() {
    mDevName = SP.getString(MainApp.gs(R.string.key_danar_bt_name), "");
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if (bluetoothAdapter != null) {
        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();

        for (BluetoothDevice device : bondedDevices) {
            if (mDevName.equals(device.getName())) {
                mBTDevice = device;
                try {
                    mRfcommSocket = mBTDevice.createRfcommSocketToServiceRecord(SPP_UUID);
                } catch (IOException e) {
                    log.error("Error creating socket: ", e);
                }
                break;
            }
        }
    } else {
        ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.nobtadapter));
    }
    if (mBTDevice == null) {
        ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.devicenotfound));
    }
}
 
Example 8
Source File: BluetoothUtils.java    From Aerlink-for-Android with MIT License 6 votes vote down vote up
public static BluetoothDevice getBondedDevice(BluetoothAdapter bluetoothAdapter) {
    BluetoothDevice bondedDevice = null;

    if (bluetoothAdapter != null) {
        try {
            Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
            if (devices != null) {
                for (BluetoothDevice device : devices) {
                    String deviceName = device.getName();
                    if (deviceName != null && (deviceName.equals("Aerlink") || deviceName.equals("BLE Utility") || deviceName.equals("Blank"))) {
                        bondedDevice = device;
                        break;
                    }
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    return bondedDevice;
}
 
Example 9
Source File: Bluetooth.java    From Arduino-Android-Bluetooth with GNU General Public License v2.0 5 votes vote down vote up
public void connectDevice(String deviceName) {
    // Get the device MAC address
    String address = null;
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    for(BluetoothDevice d: adapter.getBondedDevices()){
        if (d.getName().equals(deviceName)) address = d.getAddress();
    }

    try {
        BluetoothDevice device = adapter.getRemoteDevice(address); // Get the BluetoothDevice object
        this.connect(device); // Attempt to connect to the device
    } catch (Exception e){
        Log.e("Unable to connect to device address "+ address,e.getMessage());
    }
}
 
Example 10
Source File: BluetoothUtils.java    From microbit with Apache License 2.0 5 votes vote down vote up
public static int getTotalPairedMicroBitsFromSystem() {
    int totalPairedMicroBits = 0;
    BluetoothAdapter mBluetoothAdapter = ((BluetoothManager) MBApp.getApp().getSystemService(Context
            .BLUETOOTH_SERVICE)).getAdapter();
    if(mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        for(BluetoothDevice bt : pairedDevices) {
            if(bt.getName().contains("micro:bit")) {
                ++totalPairedMicroBits;
            }
        }
    }
    return totalPairedMicroBits;
}
 
Example 11
Source File: BluetoothUtils.java    From microbit with Apache License 2.0 5 votes vote down vote up
public static ConnectedDevice getPairedMicrobit(Context ctx) {
    SharedPreferences pairedDevicePref = ctx.getApplicationContext().getSharedPreferences(PREFERENCES_KEY,
            Context.MODE_MULTI_PROCESS);

    if(sConnectedDevice == null) {
        sConnectedDevice = new ConnectedDevice();
    }

    if(pairedDevicePref.contains(PREFERENCES_PAIREDDEV_KEY)) {
        boolean pairedMicrobitInSystemList = false;
        String pairedDeviceString = pairedDevicePref.getString(PREFERENCES_PAIREDDEV_KEY, null);
        Gson gson = new Gson();
        sConnectedDevice = gson.fromJson(pairedDeviceString, ConnectedDevice.class);
        //Check if the microbit is still paired with our mobile
        BluetoothAdapter mBluetoothAdapter = ((BluetoothManager) MBApp.getApp().getSystemService(Context
                .BLUETOOTH_SERVICE)).getAdapter();
        if(mBluetoothAdapter.isEnabled()) {
            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
            for(BluetoothDevice bt : pairedDevices) {
                if(bt.getAddress().equals(sConnectedDevice.mAddress)) {
                    pairedMicrobitInSystemList = true;
                    break;
                }
            }
        } else {
            //Do not change the list until the Bluetooth is back ON again
            pairedMicrobitInSystemList = true;
        }

        if(!pairedMicrobitInSystemList) {
            Log.e("BluetoothUtils", "The last paired microbit is no longer in the system list. Hence removing it");
            //Return a NULL device & update preferences
            sConnectedDevice.mPattern = null;
            sConnectedDevice.mName = null;
            sConnectedDevice.mStatus = false;
            sConnectedDevice.mAddress = null;
            sConnectedDevice.mPairingCode = 0;
            sConnectedDevice.mfirmware_version = null;
            sConnectedDevice.mlast_connection_time = 0;

            setPairedMicroBit(ctx, null);
        }
    } else {
        sConnectedDevice.mPattern = null;
        sConnectedDevice.mName = null;
    }
    return sConnectedDevice;
}
 
Example 12
Source File: BluetoothPairedListDialog.java    From an2linuxclient with GNU General Public License v3.0 5 votes vote down vote up
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);

    View view = inflater.inflate(R.layout.view_add_bluetooth_server, container);

    ListView listViewBtPairedPCs = (ListView) view.findViewById(R.id.listViewBtPairedPCs);

    ArrayList<BluetoothDevice> pairedBluetoothList = new ArrayList<>();

    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();

    if (pairedDevices.size() > 0) {
        for (BluetoothDevice device : pairedDevices) {
            if(device.getBluetoothClass().getMajorDeviceClass() == BluetoothClass.Device.Major.COMPUTER) {
                pairedBluetoothList.add(device);
            }
        }
        if (pairedBluetoothList.size() == 0) {
            Toast.makeText(getActivity().getApplicationContext(), R.string.bluetooth_no_paired_found, Toast.LENGTH_LONG).show();
            return null;
        }
    } else {
        Toast.makeText(getActivity().getApplicationContext(), R.string.bluetooth_no_paired_found, Toast.LENGTH_LONG).show();
        return null;
    }
    BluetoothPairedDevicesAdapter adapter = new BluetoothPairedDevicesAdapter(getActivity(), pairedBluetoothList, this);
    listViewBtPairedPCs.setAdapter(adapter);
    return view;
}
 
Example 13
Source File: OBD2Handler.java    From react-native-obd2 with MIT License 5 votes vote down vote up
public Set<BluetoothDevice> getBondedDevices() throws IOException {
  if (!mPreRequisites) {
    throw new IOException("Bluetooth is not enabled");
  }

  final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
  if (btAdapter == null || !btAdapter.isEnabled()) {
    throw new IOException("This device does not support Bluetooth or it is disabled.");
  }

  Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
  return pairedDevices;
}
 
Example 14
Source File: BluetoothListPreference.java    From CarBusInterface with MIT License 5 votes vote down vote up
public BluetoothListPreference(final Context context, final AttributeSet attrs) {
    super(context, attrs);

    if (D) Log.d(TAG, "BluetoothListPreference()");

    CharSequence[] entries = new CharSequence[1];
    CharSequence[] values = new CharSequence[1];

    Set<BluetoothDevice> devices = null;

    final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

    if (adapter != null) {
        devices = adapter.getBondedDevices();

        if (devices.size() > 0) {
            entries = new CharSequence[devices.size()];
            values = new CharSequence[devices.size()];
            int i = 0;
            for (BluetoothDevice device : devices) {
                entries[i] = device.getName();
                values[i] = device.getAddress();
                i++;
            }
        }
    }

    if (devices == null || devices.size() <= 0) {
        entries[0] = context.getResources().getString(R.string.msg_error_no_bluetooth);
        values[0] = "";
    }

    setEntries(entries);
    setEntryValues(values);
}
 
Example 15
Source File: DeviceFinder.java    From brailleback with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of bonded and supported devices in the order they
 * should be tried.
 */
public List<DeviceInfo> findDevices() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter == null) {
        return Collections.emptyList();
    }

    List<DeviceInfo> ret = new ArrayList<DeviceInfo>();
// getBondedDevices() may contain null.
Set<BluetoothDevice> bondedDevices = adapter.getBondedDevices();
if (bondedDevices == null) {
  return ret;
}
    for (BluetoothDevice dev : bondedDevices) {
  if (dev == null) {
    continue;
  }
        for (SupportedDevice matcher : SUPPORTED_DEVICES) {
            DeviceInfo matched = matcher.match(dev);
            if (matched != null) {
                ret.add(matched);
            }
        }
    }
    String lastAddress = mSharedPreferences.getString(
        LAST_CONNECTED_DEVICE_KEY, null);
    if (lastAddress != null) {
        // If the last device that was successfully connected is
        // not already first in the list, put it there.
        // (Hence, the 1 below is intentional).
        for (int i = 1; i < ret.size(); ++i) {
            if (ret.get(i).getBluetoothDevice().getAddress().equals(
                    lastAddress)) {
                Collections.swap(ret, 0, i);
            }
        }
    }
    return ret;
}
 
Example 16
Source File: BluetoothInfo.java    From MobileInfo with Apache License 2.0 5 votes vote down vote up
@SuppressLint("MissingPermission")
static JSONObject getMobBluetooth(Context context) {
    BluetoothBean bluetoothBean = new BluetoothBean();
    try {
        bluetoothBean.setBluetoothAddress(Settings.Secure.getString(context.getContentResolver(), "bluetooth_address"));
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            return bluetoothBean.toJSONObject();
        }
        bluetoothBean.setEnabled(bluetoothAdapter.isEnabled());
        bluetoothBean.setPhoneName(bluetoothAdapter.getName());
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        List<JSONObject> list = new ArrayList<>();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                BluetoothBean.DeviceBean deviceBean = new BluetoothBean.DeviceBean();
                deviceBean.setAddress(device.getAddress());
                deviceBean.setName(device.getName());
                list.add(deviceBean.toJSONObject());
            }
        }
        bluetoothBean.setDevice(list);
    } catch (Exception e) {
        Log.e(TAG, e.toString());
    }
    return bluetoothBean.toJSONObject();
}
 
Example 17
Source File: BluetoothUtils.java    From Android-BluetoothKit with Apache License 2.0 5 votes vote down vote up
public static List<BluetoothDevice> getBondedBluetoothClassicDevices() {
    BluetoothAdapter adapter = getBluetoothAdapter();
    List<BluetoothDevice> devices = new ArrayList<BluetoothDevice>();
    if (adapter != null) {
        Set<BluetoothDevice> sets = adapter.getBondedDevices();
        if (sets != null) {
            devices.addAll(sets);
        }
    }
    return devices;
}
 
Example 18
Source File: BTDeviceSkillViewFragment.java    From Easer with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
private String resolveHWAddress(String hwaddress) {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter != null) {
        for (BluetoothDevice btDevice : bluetoothAdapter.getBondedDevices()) {
            if (btDevice.getAddress().equals(hwaddress)) {
                return btDevice.getName();
            }
        }
    }
    return null;
}
 
Example 19
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
private void startSyncProxyService() {
	boolean isPaired = false;
	BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

	if( btAdapter != null ) {
		if( btAdapter.isEnabled() && btAdapter.getBondedDevices() != null && !btAdapter.getBondedDevices().isEmpty() ) {
			for( BluetoothDevice device : btAdapter.getBondedDevices() ) {
				if( device.getName() != null && device.getName().contains( getString( R.string.device_name ) ) ) {
					isPaired = true;
					break;
				}
			}
		}

		if( isPaired ) {
			if( AppLinkService.getInstance() == null ) {
				Intent appLinkServiceIntent = new Intent( this, AppLinkService.class );
				startService( appLinkServiceIntent );
			} else {
				SyncProxyALM proxyInstance = AppLinkService.getInstance().getProxy();
				if( proxyInstance == null ) {
					AppLinkService.getInstance().startProxy();
				}
			}
		}
	}
}
 
Example 20
Source File: AddVoiceSettingActivity.java    From your-local-weather with GNU General Public License v3.0 4 votes vote down vote up
private void populateTriggerBtDevices(int spinnerViewId, int checkBoxViewId, VoiceSettingParamType voiceSettingParamType) {
    MultiSelectionTriggerSpinner btDevicesSpinner = findViewById(spinnerViewId);
    CheckBox allBtCheckbox = findViewById(checkBoxViewId);
    btDevicesSpinner.setVoiceSettingId(voiceSettingId);

    BluetoothAdapter bluetoothAdapter = Utils.getBluetoothAdapter(getBaseContext());

    if (bluetoothAdapter == null) {
        btDevicesSpinner.setVisibility(View.GONE);
        allBtCheckbox.setVisibility(View.GONE);
        return;
    } else {
        btDevicesSpinner.setVisibility(View.VISIBLE);
        allBtCheckbox.setVisibility(View.VISIBLE);
    }

    Set<BluetoothDevice> bluetoothDeviceSet = bluetoothAdapter.getBondedDevices();

    ArrayList<MultiselectionItem> items = new ArrayList<>();
    ArrayList<MultiselectionItem> selection = new ArrayList<>();
    ArrayList<String> selectedItems = new ArrayList<>();

    String enabledBtDevices = voiceSettingParametersDbHelper.getStringParam(
            voiceSettingId,
            voiceSettingParamType.getVoiceSettingParamTypeId());
    Boolean enabledVoiceDevices = voiceSettingParametersDbHelper.getBooleanParam(
            voiceSettingId,
            voiceSettingParamType.getVoiceSettingParamTypeId());
    if ((enabledVoiceDevices != null) && enabledVoiceDevices) {
        allBtCheckbox.setChecked(true);
        findViewById(R.id.trigger_bt_when_devices).setVisibility(View.GONE);
    } else {
        findViewById(R.id.trigger_bt_when_devices).setVisibility(View.VISIBLE);
    }

    if (enabledBtDevices != null) {
        for (String btDeviceAddress: enabledBtDevices.split(",")) {
            selectedItems.add(btDeviceAddress);
        }
    }

    for(BluetoothDevice bluetoothDevice: bluetoothDeviceSet) {
        String currentDeviceName = bluetoothDevice.getName();
        String currentDeviceAddress = bluetoothDevice.getAddress();
        MultiselectionItem multiselectionItem;
        if (selectedItems.contains(currentDeviceAddress)) {
            multiselectionItem = new MultiselectionItem(currentDeviceName, currentDeviceAddress, true);
            selection.add(multiselectionItem);
        } else {
            multiselectionItem = new MultiselectionItem(currentDeviceName, currentDeviceAddress,false);
        }
        items.add(multiselectionItem);
    }
    btDevicesSpinner.setItems(items);
    btDevicesSpinner.setSelection(selection);
}