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

The following examples show how to use android.bluetooth.BluetoothDevice#getAddress() . 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: ConnectReceiver.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    try {
        //noinspection ConstantConditions
        if (intent.getAction().equals("android.bluetooth.device.action.ACL_CONNECTED")) {
            final BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
            if (device != null) {
                final String address = device.getAddress();
                if (address != null) {
                    UserError.Log.d(TAG, "Connection notice: " + address);
                    processCallBacks(address, "CONNECTED", device);
                }
            }
        }
    } catch (NullPointerException e) {
        UserError.Log.e(TAG, "NPE in onReceive: " + e);
    }
}
 
Example 2
Source File: BluetoothView.java    From android_tv_metro with Apache License 2.0 6 votes vote down vote up
@Override
public void connected(BluetoothDevice device) {
    String address = null;
    if(device != null){
        address = device.getAddress();
    }
    if(TextUtils.isEmpty(address)){
        return;
    }
    synchronized(mHandlerObject){
        if(!mHandlerList.contains(address)){
            mHandlerList.add(address);
            refreshList();
        }
    }
}
 
Example 3
Source File: DisplayService.java    From brailleback with Apache License 2.0 6 votes vote down vote up
/**
 * If {@code intent} indicates that a new device has been
 * paired, try to connect to it.
 */
private void connectFromBroadcastIntent(Intent intent) {
    if (mConnectionState == STATE_CONNECTED) {
        return;
    }
    int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,
            BluetoothDevice.BOND_NONE);
    if (bondState != BluetoothDevice.BOND_BONDED) {
        return;
    }
    BluetoothDevice bthDev = intent.getParcelableExtra(
            BluetoothDevice.EXTRA_DEVICE);
    if (bthDev == null) {
        return;
    }
    mPendingBluetoothAddress = bthDev.getAddress();
    connectBraille();
}
 
Example 4
Source File: NovarumbluetoothModule.java    From NovarumBluetooth with MIT License 6 votes vote down vote up
@Kroll.method
public KrollDict getPairedDevices()
{
	Log.d(TAG, "getPairedDevices called");
	
	Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
	
	KrollDict result = new KrollDict();
	
	// If there are paired devices
	if (pairedDevices.size() > 0) 
	{
	    // Loop through paired devices
	    for (BluetoothDevice device : pairedDevices) 
	    {
	    	//Halilk: for some devices, device name is the same so put some of mac digits
	    	String strDigitstoAdd = device.getAddress();
	    	strDigitstoAdd = strDigitstoAdd.replace(":","");
	    	result.put(device.getName()+"_"+strDigitstoAdd, device.getAddress());		    	
	    }
	}
	
	return result;
	
}
 
Example 5
Source File: BluetoothLE.java    From Makeblock-App-For-Android with MIT License 6 votes vote down vote up
public List<String> getDeviceList(){
        
        List<String> data = new ArrayList<String>();
//      prDevices.clear();
        for(int i=0;i<mDevices.getCount();i++){
        	BluetoothDevice dev = mDevices.getDevice(i);
        	String s = dev.getName();
        	if(s!=null){
	        	if(s.indexOf("null")>-1){
	        		s = "Bluetooth";
	        	}
        	}else{
        		s = "Bluetooth";
        	}
        	//String[] a = dev.getAddress().split(":");
        	if(mCurrentDevice!=null){
        		s=s+" "+dev.getAddress()+" "+(dev.getBondState()==BluetoothDevice.BOND_NONE?((mCurrentDevice!=null && mCurrentDevice.equals(dev))?mContext.getString(R.string.connected):mContext.getString(R.string.unbond)):mContext.getString(R.string.bonded));
        	}else{
        		s=s+" "+dev.getAddress()+" "+(dev.getBondState()==BluetoothDevice.BOND_BONDED?mContext.getString(R.string.bonded):mContext.getString(R.string.unbond));
        	}
        	data.add(s);
        }
        return data;
    }
 
Example 6
Source File: BluetoothBackendHelper.java    From android_external_UnifiedNlpApi with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
        bluetooths.clear();
    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
        onBluetoothChanged();
    } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);
        Bluetooth bluetoothDiscovered = new Bluetooth(device.getAddress(), device.getName(), rssi);
        bluetooths.add(bluetoothDiscovered);
    }
}
 
Example 7
Source File: BluetoothManager.java    From tap-android-sdk with Apache License 2.0 5 votes vote down vote up
private void establishConnection(String deviceAddress) {

        log("Establishing connection with " + deviceAddress);

        if (bluetoothAdapter == null) {
            notifyOnError(EMPTY_DEVICE_ADDRESS, ERR_C_BLUETOOTH_NOT_SUPPORTED, ErrorStrings.BLUETOOTH_NOT_SUPPORTED);
            return;
        }

        for (String connectedDeviceAddress: getConnectedDevices()) {
            notifyOnDeviceAlreadyConnected(connectedDeviceAddress);
        }

        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
        if (bondedDevices == null) {
            notifyOnError(EMPTY_DEVICE_ADDRESS, ERR_C_PAIRED_DEVICES, ErrorStrings.PAIRED_DEVICES);
            return;
        }

        for (BluetoothDevice bondedDevice : bondedDevices) {
            String bondedDeviceAddress = bondedDevice.getAddress();
            log(bondedDeviceAddress + " " + deviceAddress);
            if (bondedDeviceAddress.equals(deviceAddress)) {
                if (!establishConnectionSent.contains(bondedDeviceAddress)) {
                    establishConnectionSent.add(bondedDeviceAddress);
                    establishConnection(bondedDevice);
                }
            }
        }
    }
 
Example 8
Source File: SamsungBle.java    From GizwitsBLE with Apache License 2.0 5 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothDevice device, int status) {
	String address = device.getAddress();
	if (status != BluetoothGatt.GATT_SUCCESS) {
		disconnect(address);
		mService.bleGattDisConnected(address);
		mService.requestProcessed(address,
				RequestType.DISCOVER_SERVICE, false);
		return;
	}
	mService.bleServiceDiscovered(device.getAddress());
}
 
Example 9
Source File: DeviceListAdapter.java    From BLEService with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public View getView(int position, View convertView, ViewGroup parent) {
	// get already available view or create new if necessary
	FieldReferences fields;
       if (convertView == null) {
       	convertView = mInflater.inflate(R.layout.activity_scanning_item, null);
       	fields = new FieldReferences();
       	fields.deviceAddress = (TextView)convertView.findViewById(R.id.deviceAddress);
       	fields.deviceName    = (TextView)convertView.findViewById(R.id.deviceName);
       	fields.deviceRssi    = (TextView)convertView.findViewById(R.id.deviceRssi);
           convertView.setTag(fields);
       } else {
           fields = (FieldReferences) convertView.getTag();
       }			
	
       // set proper values into the view
       BluetoothDevice device = mDevices.get(position);
       int rssi = mRSSIs.get(position);
       String rssiString = (rssi == 0) ? "N/A" : rssi + " db";
       String name = device.getName();
       String address = device.getAddress();
       if(name == null || name.length() <= 0) name = "Unknown Device";
       
       fields.deviceName.setText(name);
       fields.deviceAddress.setText(address);
       fields.deviceRssi.setText(rssiString);

	return convertView;
}
 
Example 10
Source File: HeartRateService.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
public HeartRateService(final BluetoothDevice device) {
    super(device.getAddress());
    if (device.getName() != null && device.getName().length() > 0) {
        setName(device.getName());
    } else {
        setName(device.getAddress());
    }
    setNetworkType(NetworkType.BLE);
}
 
Example 11
Source File: Device.java    From gilgamesh with GNU General Public License v3.0 5 votes vote down vote up
public Device (BluetoothDevice bDevice)
{
	mAddress = bDevice.getAddress();
	mName = GilgaService.mapToNickname(mAddress);
	mType = TYPE_BLUETOOTH_CLASSIC;
	mTrusted = bDevice.getBondState() == BluetoothDevice.BOND_BONDED;
	
	mInstance = bDevice;
}
 
Example 12
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 13
Source File: BTDeviceProfile.java    From BLEService with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public BTDeviceProfile(BluetoothDevice device, BluetoothGatt gatt, int connectionState) {
	mDeviceAddress = device.getAddress();
	mConnectionState = connectionState;
	mServiceProfileList = new ArrayList<BTServiceProfile>();
	for (BluetoothGattService service : gatt.getServices()) {
		BTServiceProfile serviceProfile = new BTServiceProfile(service);
		mServiceProfileList.add(serviceProfile);
	}
}
 
Example 14
Source File: BluetoothA2dpSnippet.java    From mobly-bundled-snippets with Apache License 2.0 5 votes vote down vote up
@Rpc(description = "Disconnects a device from A2DP profile.")
public void btA2dpDisconnect(String deviceAddress) throws Throwable {
    BluetoothDevice device = getConnectedBluetoothDevice(deviceAddress);
    Utils.invokeByReflection(sA2dpProfile, "disconnect", device);
    if (!Utils.waitUntil(
            () -> sA2dpProfile.getConnectionState(device) == BluetoothA2dp.STATE_DISCONNECTED,
            120)) {
        throw new BluetoothA2dpSnippetException(
                "Failed to disconnect device "
                        + device.getName()
                        + "|"
                        + device.getAddress()
                        + " from A2DP profile within 2min.");
    }
}
 
Example 15
Source File: BleRequestImpl.java    From Android-BLE with Apache License 2.0 4 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                    int newState) {
    BluetoothDevice device = gatt.getDevice();
    if (device == null){
        return;
    }
    String address = device.getAddress();
    //remove timeout callback
    cancelTimeout(address);
    T bleDevice = getBleDeviceInternal(address);
    //There is a problem here Every time a new object is generated that causes the same device to be disconnected and the connection produces two objects
    if (status == BluetoothGatt.GATT_SUCCESS) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            connectedAddressList.add(device.getAddress());
            if (connectWrapperCallback != null){
                bleDevice.setConnectionState(BleDevice.CONNECTED);
                connectWrapperCallback.onConnectionChanged(bleDevice);
            }
            BleLog.d(TAG, "onConnectionStateChange:----device is connected.");
            BluetoothGatt bluetoothGatt = gattHashMap.get(device.getAddress());
            if (null != bluetoothGatt){
                // Attempts to discover services after successful connection.
                BleLog.d(TAG, "trying to start service discovery");
                bluetoothGatt.discoverServices();
            }
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            BleLog.d(TAG, "onConnectionStateChange:----device is disconnected.");
            if (connectWrapperCallback != null){
                bleDevice.setConnectionState(BleDevice.DISCONNECT);
                connectWrapperCallback.onConnectionChanged(bleDevice);
            }
            close(device.getAddress());
        }
    } else {
        //Occurrence 133 or 257 19 Equal value is not 0: Connection establishment failed due to protocol stack
        BleLog.e(TAG, "onConnectionStateChange----: " + "Connection status is abnormal:" + status);
        close(device.getAddress());
        if (connectWrapperCallback != null){
            int errorCode = getErrorCode(bleDevice);
            connectWrapperCallback.onConnectException(bleDevice, errorCode);
            bleDevice.setConnectionState(BleDevice.DISCONNECT);
            connectWrapperCallback.onConnectionChanged(bleDevice);
        }
    }

}
 
Example 16
Source File: MainActivity.java    From mcumgr-android with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(@Nullable final Bundle savedInstanceState) {
    // The target must be set before calling super.onCreate(Bundle).
    // Otherwise, Dagger2 will fail to inflate this Activity.
    final BluetoothDevice device = getIntent().getParcelableExtra(EXTRA_DEVICE);
    final String deviceName = device.getName();
    final String deviceAddress = device.getAddress();
    ((Dagger2Application) getApplication()).setTarget(device);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new ViewModelProvider(this, mViewModelFactory)
            .get(MainViewModel.class);

    // Configure the view.
    final Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle(deviceName);
    getSupportActionBar().setSubtitle(deviceAddress);

    final BottomNavigationView navMenu = findViewById(R.id.nav_menu);
    navMenu.setSelectedItemId(R.id.nav_default);
    navMenu.setOnNavigationItemSelectedListener(item -> {
        switch (item.getItemId()) {
            case R.id.nav_default:
                getSupportFragmentManager().beginTransaction()
                        .show(mDeviceFragment).hide(mImageFragment)
                        .hide(mFilesFragment).hide(mLogsStatsFragment)
                        .commit();
                return true;
            case R.id.nav_dfu:
                getSupportFragmentManager().beginTransaction()
                        .hide(mDeviceFragment).show(mImageFragment)
                        .hide(mFilesFragment).hide(mLogsStatsFragment)
                        .commit();
                return true;
            case R.id.nav_fs:
                getSupportFragmentManager().beginTransaction()
                        .hide(mDeviceFragment).hide(mImageFragment)
                        .show(mFilesFragment).hide(mLogsStatsFragment)
                        .commit();
                return true;
            case R.id.nav_stats:
                getSupportFragmentManager().beginTransaction()
                        .hide(mDeviceFragment).hide(mImageFragment)
                        .hide(mFilesFragment).show(mLogsStatsFragment)
                        .commit();
                return true;
        }
        return false;
    });

    // Initialize fragments.
    if (savedInstanceState == null) {
        mDeviceFragment = new DeviceFragment();
        mImageFragment = new ImageFragment();
        mFilesFragment = new FilesFragment();
        mLogsStatsFragment = new LogsStatsFragment();

        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, mDeviceFragment, "device")
                .add(R.id.container, mImageFragment, "image")
                .add(R.id.container, mFilesFragment, "fs")
                .add(R.id.container, mLogsStatsFragment, "logs")
                // Initially, show the Device fragment and hide others.
                .hide(mImageFragment).hide(mFilesFragment).hide(mLogsStatsFragment)
                .commit();
    } else {
        mDeviceFragment = getSupportFragmentManager().findFragmentByTag("device");
        mImageFragment = getSupportFragmentManager().findFragmentByTag("image");
        mFilesFragment = getSupportFragmentManager().findFragmentByTag("fs");
        mLogsStatsFragment = getSupportFragmentManager().findFragmentByTag("logs");
    }
}
 
Example 17
Source File: BlueToothService.java    From EFRConnect-android with Apache License 2.0 4 votes vote down vote up
boolean addDiscoveredDevice(ScanResultCompat result) {


        Log.d(TAG, "addDiscoveredDevice: " + result);


        if (knownDevice.get() != null) {
            return true;
        }

        final ArrayList<BluetoothDeviceInfo> listenerResult;
        final BluetoothDeviceInfo listenerChanged;
        final boolean postNewDiscoveryTimeout;

        BluetoothDevice device = result.getDevice();
        BluetoothDeviceInfo devInfo;
        synchronized (discoveredDevices) {
            final String address = device.getAddress();

            devInfo = discoveredDevices.get(address);
            if (devInfo == null) {
                devInfo = new BluetoothDeviceInfo();
                devInfo.device = device;
                discoveredDevices.put(address, devInfo);
                postNewDiscoveryTimeout = true;
            } else {
                devInfo.device = device;
                postNewDiscoveryTimeout = false;
            }
            devInfo.scanInfo = result;

            if (!devInfo.isConnectable) {
                devInfo.isConnectable = result.isConnectable();
            }

            devInfo.count++;

            if (devInfo.timestampLast == 0) {
                devInfo.timestampLast = result.getTimestampNanos();
            } else {
                devInfo.setIntervalIfLower(result.getTimestampNanos() - devInfo.timestampLast);
                devInfo.timestampLast = result.getTimestampNanos();
            }

            devInfo.rawData = ScanRecordParser.getRawAdvertisingDate(result.getScanRecord().getBytes());

            if (isDeviceInteresting(device)) {
                devInfo.isNotOfInterest = false;
                devInfo.isOfInterest = true;
                if (!interestingDevices.containsKey(address)) {
                    interestingDevices.put(address, devInfo);
                }
            } else if (isDeviceNotInteresting(device)) {
                devInfo.isNotOfInterest = true;
                devInfo.isOfInterest = false;
            }

            if (!listeners.isEmpty()) {
                listenerResult = new ArrayList<>(discoveredDevices.size());
                listenerChanged = devInfo.clone();
                for (BluetoothDeviceInfo di : discoveredDevices.values()) {
                    if (!isDeviceNotInteresting(di.device)) {
                        listenerResult.add(di.clone());
                    }
                }
            } else {
                listenerResult = null;
                listenerChanged = null;
            }
        }

        if (listenerResult != null) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    listeners.onScanResultUpdated(listenerResult, listenerChanged);
                }
            });
        }

        return false;
    }
 
Example 18
Source File: ThunderBoardDevice.java    From thunderboard-android with Apache License 2.0 4 votes vote down vote up
public ThunderBoardDevice(BluetoothDevice device, int rssi) {
    this.name = device.getName();
    this.address = device.getAddress();
    this.rssi = rssi;
    this.isOriginalNameNull = false;
}
 
Example 19
Source File: BluetoothScan.java    From xDrip-Experimental with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    Log.d(TAG, "Item Clicked");
    final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
    if (device == null || device.getName() == null) return;
    Toast.makeText(this, R.string.connecting_to_device, Toast.LENGTH_LONG).show();

    ActiveBluetoothDevice btDevice = new Select().from(ActiveBluetoothDevice.class)
            .orderBy("_ID desc")
            .executeSingle();

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    prefs.edit().putString("last_connected_device_address", device.getAddress()).apply();
    if (btDevice == null) {
        ActiveBluetoothDevice newBtDevice = new ActiveBluetoothDevice();
        newBtDevice.name = device.getName();
        newBtDevice.address = device.getAddress();
        newBtDevice.save();
    } else {
        btDevice.name = device.getName();
        btDevice.address = device.getAddress();
        btDevice.save();
    }
    if(device.getName().toLowerCase().contains("dexcom")) {
        if(!CollectionServiceStarter.isBTShare(getApplicationContext())) {
            prefs.edit().putString("dex_collection_method", "DexcomShare").apply();
            prefs.edit().putBoolean("calibration_notifications", false).apply();
        }
        if(prefs.getString("share_key", "SM00000000").compareTo("SM00000000") == 0 || prefs.getString("share_key", "SM00000000").length() < 10) {
            requestSerialNumber(prefs);
        } else returnToHome();

    } else if(device.getName().toLowerCase().contains("bridge")) {
        if(!CollectionServiceStarter.isDexbridgeWixelorWifiandDexbridgeWixel(getApplicationContext()))
            prefs.edit().putString("dex_collection_method", "DexbridgeWixel").apply();
        if(prefs.getString("dex_txid", "00000").compareTo("00000") == 0 || prefs.getString("dex_txid", "00000").length() < 5) {
            requestTransmitterId(prefs);
        } else returnToHome();

    } else if(device.getName().toLowerCase().contains("drip")) {
        if (!
                (CollectionServiceStarter.isBteWixelorWifiandBtWixel(getApplicationContext())
                ) || CollectionServiceStarter.isLimitter(getApplicationContext())) {
            prefs.edit().putString("dex_collection_method", "BluetoothWixel").apply();
        }
        returnToHome();
    } else if(device.getName().toLowerCase().contains("limitter")) {
        if (!CollectionServiceStarter.isLimitter(getApplicationContext())) {
            prefs.edit().putString("dex_collection_method", "LimiTTer").apply();
        }
        returnToHome();
    } else {
        returnToHome();
    }
}
 
Example 20
Source File: BluetoothController.java    From blue-pair with MIT License 2 votes vote down vote up
/**
 * Converts a BluetoothDevice to its String representation.
 *
 * @param device the device to convert to String.
 * @return a String representation of the device.
 */
public static String deviceToString(BluetoothDevice device) {
    return "[Address: " + device.getAddress() + ", Name: " + device.getName() + "]";
}