android.bluetooth.BluetoothDevice Java Examples

The following examples show how to use android.bluetooth.BluetoothDevice. 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: DexShareCollectionService.java    From xDrip-Experimental with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    Log.d(TAG, "characteristic wrote " + status);
    if (status == BluetoothGatt.GATT_SUCCESS) {
        Log.d(TAG, "Wrote a characteristic successfully " + characteristic.getUuid());
        if (mAuthenticationCharacteristic.getUuid().equals(characteristic.getUuid())) {
            state_authSucess = true;
            gatt.readCharacteristic(mHeartBeatCharacteristic);
        }
    } else if ((status & BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) != 0 || (status & BluetoothGatt.GATT_INSUFFICIENT_ENCRYPTION) != 0) {
        if (gatt.getDevice().getBondState() == BluetoothDevice.BOND_NONE) {
            device = gatt.getDevice();
            state_authInProgress = true;
            bondDevice();
        } else {
            Log.e(TAG, "The phone is trying to read from paired device without encryption. Android Bug? Have the dexcom forget whatever device it was previously paired to");
        }
    } else {
        Log.e(TAG, "Unknown error writing Characteristic");
    }
}
 
Example #2
Source File: FitbitBluetoothDevice.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
public FitbitBluetoothDevice(@NonNull BluetoothDevice device) {
    this.device = device;
    this.bluetoothAddress = device.getAddress();
    // this can throw a parcelable null pointer exception down in the stack
    try {
        this.name = new GattUtils().debugSafeGetBtDeviceName(device);
    } catch (NullPointerException ex) {
        this.name = "Unknown Device";
    }
}
 
Example #3
Source File: DeviceListActivity.java    From Android-nRF-UART with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void onStart() {
    super.onStart();
   
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
}
 
Example #4
Source File: TemplateService.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void onSampleValueReceived(@NonNull final BluetoothDevice device, final int value) {
    final Intent broadcast = new Intent(BROADCAST_TEMPLATE_MEASUREMENT);
    broadcast.putExtra(EXTRA_DEVICE, getBluetoothDevice());
    broadcast.putExtra(EXTRA_DATA, value);
    LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast);

    if (!bound) {
        // Here we may update the notification to display the current value.
        // TODO modify the notification here
    }
}
 
Example #5
Source File: DeviceListActivity.java    From Android-BLE-Terminal with MIT License 5 votes vote down vote up
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    addDevice(device, rssi);
                }
            });

        }
    });
}
 
Example #6
Source File: TimeZoneDataCallback.java    From Android-BLE-Common-Library with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
	super.onDataReceived(device, data);

	final Integer offset = readTimeZone(data, 0);
	if (offset == null) {
		onInvalidDataReceived(device, data);
		return;
	}

	if (offset == -128) {
		onUnknownTimeZoneReceived(device);
	} else if (offset < -48 || offset > 56) {
		onInvalidDataReceived(device, data);
	} else {
		onTimeZoneReceived(device, offset * 15);
	}
}
 
Example #7
Source File: BluetoothServerService.java    From tilt-game-android with MIT License 5 votes vote down vote up
private synchronized void accepted(BluetoothSocket socket, BluetoothDevice device, String socketType) {
    if (_debug) Log.d(TAG, "accepted, Socket Type:" + socketType);

    // Start the thread to manage the connection and perform transmissions
    createCommunicationThread(socket, device);

    // Send the name of the connected device back to the UI Activity
    Bundle bundle = new Bundle();
    bundle.putString(ServiceMessageKeys.DEVICE_NAME, device.getName());
    bundle.putString(ServiceMessageKeys.DEVICE_ADDRESS, device.getAddress());
    sendMessage(ServiceMessageType.MESSAGE_DEVICE_ADDED, bundle);
}
 
Example #8
Source File: PairedListAdapter.java    From ELM327 with Apache License 2.0 5 votes vote down vote up
@Override
public BluetoothDevice getItem(int position)
{
    if (mDeviceList == null)
        return null;
    else
        return mDeviceList.get(position);
}
 
Example #9
Source File: MainActivity.java    From PodEmu with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent)
{
    try
    {
        String action = intent.getAction();


        if(action.contains(BluetoothDevice.ACTION_ACL_CONNECTED)
                && (((BluetoothDevice)intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)).getName() == SerialInterface_BT.getInstance().getName()))
        {
            PodEmuLog.debug("MA: Bluetooth device '" + SerialInterface_BT.getInstance().getName() + "' connected.");
            start_service();
        }
        else
        {
            PodEmuLog.debug("MA: broadcast processing requested");
            PodEmuMessage podEmuMessage = PodEmuIntentFilter.processBroadcast(context, intent);
            // if null is received then broadcast could be not from "our" app
            if (podEmuMessage != null)
            {
                PodEmuLog.debug("MA: received PodEmuMessage");
                currentlyPlaying.bulk_update(podEmuMessage);
                if (podEmuMessage.getAction() != PodEmuMessage.ACTION_QUEUE_CHANGED)
                {
                    updateCurrentlyPlayingDisplay();
                }
            }
        }

    }
    catch(Exception e)
    {
        PodEmuLog.printStackTrace(e);
        throw e;
    }

}
 
Example #10
Source File: BluetoothCentralTest.java    From blessed-android with MIT License 5 votes vote down vote up
@Test
public void cancelConnectionReconnectingPeripheralTest() throws Exception {
    application.grantPermissions(Manifest.permission.ACCESS_COARSE_LOCATION);

    BluetoothPeripheral peripheral = mock(BluetoothPeripheral.class);
    when(peripheral.getAddress()).thenReturn("12:23:34:98:76:54");
    when(peripheral.getType()).thenReturn(BluetoothDevice.DEVICE_TYPE_UNKNOWN);

    central.autoConnectPeripheral(peripheral, peripheralCallback);

    central.cancelConnection(peripheral);

    verify(callback).onDisconnectedPeripheral(peripheral, GATT_SUCCESS);
}
 
Example #11
Source File: BluetoothManager.java    From retrowatch with Apache License 2.0 5 votes vote down vote up
public void run() {
   	if(mIsServiceStopped)
   		return;
	
	mHandler.post(new Runnable() {
		public void run() {
	    	if(getState() == STATE_CONNECTED || getState() == STATE_CONNECTING)
	    		return;
	    	
	    	Logs.d(TAG, "ConnectTimerTask :: Retry connect()");
	    	
			ConnectionInfo cInfo = ConnectionInfo.getInstance(null);
			if(cInfo != null) {
				String addrs = cInfo.getDeviceAddress();
				BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
				if(ba != null && addrs != null) {
					BluetoothDevice device = ba.getRemoteDevice(addrs);
					
					if(device != null) {
						connect(device);
					}
				}
			}
			
			reserveRetryConnect();
		}	// End of run()
	});
}
 
Example #12
Source File: RunningSpeedAndCadenceMeasurementResponse.java    From Android-BLE-Library with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void onRSCMeasurementReceived(@NonNull final BluetoothDevice device, final boolean running,
									 final float instantaneousSpeed, final int instantaneousCadence,
									 @Nullable final Integer strideLength,
									 @Nullable final Long totalDistance) {
	this.running = running;
	this.instantaneousSpeed = instantaneousSpeed;
	this.instantaneousCadence = instantaneousCadence;
	this.strideLength = strideLength;
	this.totalDistance = totalDistance;
}
 
Example #13
Source File: BluetoothLeService.java    From IoT-Firstep with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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()) {
            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;
    return true;
}
 
Example #14
Source File: AmazonFreeRTOSManager.java    From amazon-freertos-ble-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to the BLE device, and notify the connection state via BleConnectionStatusCallback.
 *
 * @param connectionStatusCallback The callback to notify app whether the BLE connection is
 *                                 successful. Must not be null.
 * @param btDevice                 the BLE device to be connected to.
 * @param cp                       the AWSCredential used to connect to AWS IoT.
 * @param autoReconnect            auto reconnect to device after unexpected disconnect
 */
public AmazonFreeRTOSDevice connectToDevice(@NonNull final BluetoothDevice btDevice,
                                            @NonNull final BleConnectionStatusCallback connectionStatusCallback,
                                            final AWSCredentialsProvider cp,
                                            final boolean autoReconnect) {
    AmazonFreeRTOSDevice aDevice = new AmazonFreeRTOSDevice(btDevice, mContext, cp);
    mAFreeRTOSDevices.put(btDevice.getAddress(), aDevice);
    aDevice.connect(connectionStatusCallback, autoReconnect);
    return aDevice;
}
 
Example #15
Source File: GlucoseManager.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Sends the request to obtain from the glucose device all records newer than the newest one
 * from local storage. The data will be returned to Glucose Measurement characteristic as
 * a notification followed by Record Access Control Point indication with status code Success
 * or other in case of error.
 * <p>
 * Refresh button will not download records older than the oldest in the local memory.
 * E.g. if you have pressed Last and then Refresh, than it will try to get only newer records.
 * However if there are no records, it will download all existing (using {@link #getAllRecords()}).
 */
void refreshRecords() {
	if (recordAccessControlPointCharacteristic == null)
		return;
	final BluetoothDevice target = getBluetoothDevice();
	if (target == null)
		return;

	if (records.size() == 0) {
		getAllRecords();
	} else {
		mCallbacks.onOperationStarted(target);

		// obtain the last sequence number
		final int sequenceNumber = records.keyAt(records.size() - 1) + 1;

		writeCharacteristic(recordAccessControlPointCharacteristic,
				RecordAccessControlPointData.reportStoredRecordsGreaterThenOrEqualTo(sequenceNumber))
				.with((device, data) -> log(LogContract.Log.Level.APPLICATION, "\"" + RecordAccessControlPointParser.parse(data) + "\" sent"))
				.enqueue();
		// Info:
		// Operators OPERATOR_LESS_THEN_OR_EQUAL and OPERATOR_RANGE are not supported by Nordic Semiconductor Glucose Service in SDK 4.4.2.
	}
}
 
Example #16
Source File: BleManager.java    From thunderboard-android with Apache License 2.0 5 votes vote down vote up
public void connect(String deviceAddress) {

        Timber.d("%s", deviceAddress);

        if (gatt != null) {
            Timber.d("gat not null, closing and reconnecting");
            closeGatt();
            connect(deviceAddress);
            return;
        }

        final BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);

        if (device == null) {
            throw new IllegalStateException("Connecting to a non discovered device is not supported.");
        } else {
            // This is where the connection session starts
            gatt = device.connectGatt(context, false, gattManager.gattCallbacks);
            ThunderBoardDevice tbd = getDeviceFromCache(deviceAddress);
            if (tbd == null) {
                tbd = new ThunderBoardDevice(device, 0);
                devices.add(tbd);
                deviceAgeMap.put(tbd.getAddress(), System.currentTimeMillis());
            }
            tbd.setState(BluetoothProfile.STATE_CONNECTING);
            selectedDeviceMonitor.onNext(tbd);
            selectedDeviceStatusMonitor.onNext(new StatusEvent(tbd));
            return;
        }
    }
 
Example #17
Source File: BluetoothLEStack.java    From awesomesauce-rfduino with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void showFoundBluetoothDevices(Context hostActivity, OnClickListener rfduinoChosenListener) {
	//An ArrayAdapter is a connector class: the adapter automatically checks for updates in our underlying datastructure and 
	// populates the results (Bluetooth radios in our case) to the ListView to be seen by the user. 
	ArrayAdapter<BluetoothDevice> adapter = new ArrayAdapter<BluetoothDevice>(hostActivity, android.R.layout.select_dialog_item, BluetoothLEStack.discoveredDevices);
	
	AlertDialog.Builder builder = new AlertDialog.Builder(hostActivity);
	    builder.setTitle("Choose an available RFDuino radio:")
	    	   .setAdapter(adapter, rfduinoChosenListener);
	   
	builder.show();
}
 
Example #18
Source File: BluetoothManager.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
	 * Bluetooth機器の探索を開始する。
	 * bluetoothに対応していないか無効になっている時はIllegalStateException例外を投げる
	 * 新しく機器が見つかった時はBluetoothDevice.ACTION_FOUNDがブロードキャストされるので
	 * ブロードキャストレシーバーを登録しておく必要がある
	 * @throws IllegalStateException
	 */
	public void startDiscovery() throws IllegalStateException {
//		if (DEBUG) Log.v(TAG, "startDiscovery:");
		synchronized (mSync) {
			if (mAdapter.isDiscovering()) {
				// 既に探索中なら一旦キャンセルする
				mAdapter.cancelDiscovery();
			}
			// 既にペアリング済みのBluetooth機器一覧を取得する
			final Set<BluetoothDevice> pairedDevices = mAdapter.getBondedDevices();
			synchronized (mDiscoveredDeviceList) {
				mDiscoveredDeviceList.clear();
				if (pairedDevices.size() > 0) {
					for (final BluetoothDevice device : pairedDevices) {
						mDiscoveredDeviceList.add(new BluetoothDeviceInfo(device));
					}
					callOnDiscover();
				}
			}
//			if (DEBUG) Log.v(TAG, "startDiscovery:探索開始");
			mAdapter.startDiscovery();
		}
	}
 
Example #19
Source File: BluetoothLeService.java    From IoT-Firstep with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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()) {
            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;
    return true;
}
 
Example #20
Source File: BluetoothGlucoseMeter.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(21)
private void initScanCallback() {
    Log.d(TAG, "init v21 ScanCallback()");

    // v21 version
    if (Build.VERSION.SDK_INT >= 21) {
        mScanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                Log.i(TAG, "onScanResult result: " + result.toString());
                final BluetoothDevice btDevice = result.getDevice();
                scanLeDevice(false); // stop scanning
                connect(btDevice.getAddress());
            }

            @Override
            public void onBatchScanResults(List<ScanResult> results) {
                for (ScanResult sr : results) {
                    Log.i("ScanResult - Results", sr.toString());
                }
            }

            @Override
            public void onScanFailed(int errorCode) {
                Log.e(TAG, "Scan Failed Error Code: " + errorCode);
                if (errorCode == 1) {
                    Log.e(TAG, "Already Scanning: "); // + isScanning);
                    //isScanning = true;
                } else if (errorCode == 2) {
                    // reset bluetooth?
                }
            }
        };
    }
}
 
Example #21
Source File: BleManager.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void onDescriptorRead(final BluetoothGatt gatt, final BluetoothGattDescriptor descriptor, final int status) {
	if (status == BluetoothGatt.GATT_SUCCESS) {
		// The value has been read. Notify the profile and proceed with the initialization queue.
		profile.onDescriptorRead(gatt, descriptor);
		operationInProgress = false;
		nextRequest();
	} else if (status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) {
		if (gatt.getDevice().getBondState() != BluetoothDevice.BOND_NONE) {
			// This should never happen but it used to: http://stackoverflow.com/a/20093695/2115352
			DebugLogger.w(TAG, ERROR_AUTH_ERROR_WHILE_BONDED);
			onError(gatt.getDevice(), ERROR_AUTH_ERROR_WHILE_BONDED, status);
		}
	} else {
		DebugLogger.e(TAG, "onDescriptorRead error " + status);
		onError(gatt.getDevice(), ERROR_READ_DESCRIPTOR, status);
	}
}
 
Example #22
Source File: BluetoothWrapper.java    From phonegap-bluetooth-plugin with MIT License 5 votes vote down vote up
/**
 * Get the devices bonded with this device.
 *
 * @return a list of Pairs. Each pair contains members <b>a</b> and <b>b</b>:
 * <b>a</b> is the device name and <b>b</b> the device address.
 *
 * @see Pair
 */
public ArrayList<Pair<String>> getBondedDevices()
{
	Set<BluetoothDevice> bondedDevices 	= _adapter.getBondedDevices();
	ArrayList<Pair<String>> devices 	= new ArrayList<Pair<String>>();

	for(BluetoothDevice device : bondedDevices)
	{
		devices.add(new Pair<String>(device.getName(), device.getAddress()));
	}

	return devices;
}
 
Example #23
Source File: SetupActivity.java    From SightRemote with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (action.equals(BluetoothDevice.ACTION_FOUND)) {
        BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        if (!bluetoothDevices.contains(bluetoothDevice)) {
            bluetoothDevices.add(intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE));
            bluetoothDeviceAdapter.notifyDataSetChanged();
        }
    } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) bluetoothAdapter.startDiscovery();
}
 
Example #24
Source File: DexCollectionService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate() {

    if (scanMeister == null) {
        scanMeister = new ScanMeister()
                .applyKnownWorkarounds()
                .addCallBack(this, TAG);
    }

    foregroundServiceStarter = new ForegroundServiceStarter(getApplicationContext(), this);
    foregroundServiceStarter.start();
    //mContext = getApplicationContext();
    dexCollectionService = this;
    prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    listenForChangeInSettings();
    //bgToSpeech = BgToSpeech.setupTTS(mContext); //keep reference to not being garbage collected
    if (CollectionServiceStarter.isDexBridgeOrWifiandDexBridge()) {
        Log.i(TAG, "onCreate: resetting bridge_battery preference to 0");
        prefs.edit().putInt("bridge_battery", 0).apply();
        //if (Home.get_master()) GcmActivity.sendBridgeBattery(prefs.getInt("bridge_battery",-1));
    }

    cloner.dontClone(
            android.bluetooth.BluetoothDevice.class,
            android.bluetooth.BluetoothGattService.class
    );

    final IntentFilter pairingRequestFilter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
    pairingRequestFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY - 1);
    registerReceiver(mPairingRequestRecevier, pairingRequestFilter);
    Log.i(TAG, "onCreate: STARTING SERVICE: pin code: " + DEFAULT_BT_PIN);

    Blukon.unBondIfBlukonAtInit();

}
 
Example #25
Source File: DeviceScanActivity.java    From BLE-Heart-rate-variability-demo with MIT License 5 votes vote down vote up
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    final BluetoothDevice device = leDeviceListAdapter.getDevice(position);
    if (device == null)
        return;

    final Intent intent = new Intent(this, DeviceServicesActivity.class);
    intent.putExtra(DeviceServicesActivity.EXTRAS_DEVICE_NAME, device.getName());
    intent.putExtra(DeviceServicesActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
    startActivity(intent);
}
 
Example #26
Source File: BLeSerialPortService.java    From Android-BLE-Terminal with MIT License 5 votes vote down vote up
private void notifyOnDeviceFound(BluetoothDevice device) {
    for (Callback cb : callbacks.keySet()) {
        if (cb != null) {
            cb.onDeviceFound(device);
        }
    }
}
 
Example #27
Source File: Bluetooth.java    From Makeblock-App-For-Android with MIT License 5 votes vote down vote up
public List<String> getPairedList(){
       List<String> data = new ArrayList<String>();
       Set<BluetoothDevice> pairedDevices = mBTAdapter.getBondedDevices();
       prDevices.clear();
	if (pairedDevices.size() > 0) {
           for (BluetoothDevice device : pairedDevices) {
               prDevices.add(device);
           }
       }
       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 #28
Source File: MainActivity.java    From ELM327 with Apache License 2.0 5 votes vote down vote up
private void scanAroundDevices()
{
    displayLog("Try to scan around devices...");

    if (mReceiver == null)
    {
        // Register the BroadcastReceiver
        mReceiver = new DeviceBroadcastReceiver();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);
    }

    // Start scanning
    mBluetoothAdapter.startDiscovery();
}
 
Example #29
Source File: BLEProvisionLanding.java    From esp-idf-provisioning-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onPeripheralFound(BluetoothDevice device, ScanResult scanResult) {

    Log.d(TAG, "====== onPeripheralFound ===== " + device.getName());
    boolean deviceExists = false;
    String serviceUuid = "";

    if (scanResult.getScanRecord().getServiceUuids() != null && scanResult.getScanRecord().getServiceUuids().size() > 0) {
        serviceUuid = scanResult.getScanRecord().getServiceUuids().get(0).toString();
    }
    Log.d(TAG, "Add service UUID : " + serviceUuid);

    if (bluetoothDevices.containsKey(device)) {
        deviceExists = true;
    }

    if (!deviceExists) {
        listView.setVisibility(View.VISIBLE);
        bluetoothDevices.put(device, serviceUuid);
        deviceList.add(device);
        adapter.notifyDataSetChanged();
    }
}
 
Example #30
Source File: CbtManager.java    From ClassicBluetooth with Apache License 2.0 5 votes vote down vote up
/**
 * 设备连接
 *
 * @param callBack
 */
public void connectDevice(BluetoothDevice device, ConnectDeviceCallback callBack) {
    mConnCallBack = callBack;
    if (mBluetoothAdapter != null) {
        //配对蓝牙
        CbtClientService.getInstance().init(mBluetoothAdapter, device, callBack);
    }
}