Java Code Examples for android.bluetooth.BluetoothDevice

The following are top voted examples for showing how to use android.bluetooth.BluetoothDevice. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: mi-band-2   File: BLEMiBand2Helper.java   Source Code and License 13 votes vote down vote up
void findBluetoothDevice(BluetoothAdapter myBluetoothAdapter,
                                    String filter) {
    Log.d(TAG, "(*) Initialising Bluetooth connection for device: " + filter);

    if(myBluetoothAdapter.isEnabled()) {
        for (BluetoothDevice pairedDevice : myBluetoothAdapter.getBondedDevices()) {
            if (pairedDevice.getName().contains(filter /*Like MI*/)) {
                Log.d(TAG, "\tDevice Name: " +  pairedDevice.getName());
                Log.d(TAG, "\tDevice MAC: " + pairedDevice.getAddress());

                activeDevice =  pairedDevice;
                break;
            }
        }
    }

    Log.d(TAG, "\tDidnt find any device!");
}
 
Example 2
Project: iconsole-android   File: DeviceListActivity.java   Source Code and License 11 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 3
Project: igrow-android   File: DeviceScanActivity.java   Source Code and License 7 votes vote down vote up
@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@SuppressWarnings("deprecation")
protected void onListItemClick(ListView l, View v, int position, long id) {
    final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
    if (device == null) return;
    final Intent intent = new Intent(this, DeviceControlActivity.class);
    intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
    intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
    if (mScanning) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mBluetoothLeScanner.stopScan(new ScanCallback() {});
        } else {
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        mScanning = false;
    }
    startActivity(intent);
}
 
Example 4
Project: react-native-blue-manager   File: BleManager.java   Source Code and License 7 votes vote down vote up
@ReactMethod
public void connect(String peripheralUUID, Callback callback) {
	Log.d(LOG_TAG, "Connect to: " + peripheralUUID );

	synchronized(peripherals) {
		Peripheral peripheral = peripherals.get(peripheralUUID);
		Log.e(LOG_TAG, "peripheral " + peripheral);
		if (peripheral == null) {
			if (peripheralUUID != null) {
				peripheralUUID = peripheralUUID.toUpperCase();
			}
			if (BluetoothAdapter.checkBluetoothAddress(peripheralUUID)) {
				BluetoothDevice device = bluetoothAdapter.getRemoteDevice(peripheralUUID);
				peripheral = new Peripheral(device, reactContext);
				peripherals.put(peripheralUUID, peripheral);
			} else {
				callback.invoke("Invalid peripheral uuid");
				return;
			}
		}
		peripheral.connect(callback, reactContext!=null?getCurrentActivity():context);
	}
}
 
Example 5
Project: buildAPKsSamples   File: DeviceListActivity.java   Source Code and License 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);
        }
    }
}
 
Example 6
Project: Nird2   File: DroidtoothPlugin.java   Source Code and License 6 votes vote down vote up
@Override
public void onReceive(Context ctx, Intent intent) {
	String action = intent.getAction();
	if (action.equals(DISCOVERY_FINISHED)) {
		LOG.info("Discovery finished");
		ctx.unregisterReceiver(this);
		finished.countDown();
	} else if (action.equals(FOUND)) {
		BluetoothDevice d = intent.getParcelableExtra(EXTRA_DEVICE);
		if (LOG.isLoggable(INFO)) {
			LOG.info("Discovered device: " +
					scrubMacAddress(d.getAddress()));
		}
		addresses.add(d.getAddress());
	}
}
 
Example 7
Project: phonk   File: PBluetooth.java   Source Code and License 6 votes vote down vote up
@ProtoMethod(description = "Send bluetooth serial message", example = "")
@ProtoMethodParam(params = {"string"})
public NativeArray getBondedDevices() {
    start();

    Set<BluetoothDevice> listDevices = mAdapter.getBondedDevices();
    MLog.d(TAG, "listDevices " + listDevices);
    int listSize = listDevices.size();
    ProtocoderNativeArray array = new ProtocoderNativeArray(listSize);
    MLog.d(TAG, "array " + array);


    int counter = 0;
    for (BluetoothDevice b : listDevices) {
        MLog.d(TAG, "bt " + b);

        ReturnObject btDevice = new ReturnObject();
        btDevice.put("name", b.getName());
        btDevice.put("mac", b.getAddress());

        array.addPE(counter++, btDevice);
    }

    return array;
}
 
Example 8
Project: grblcontroller   File: SerialThreadService.java   Source Code and License 6 votes vote down vote up
public ConnectThread(BluetoothDevice device, boolean secure) {
    mmDevice = device;
    BluetoothSocket tmp = null;
    mSocketType = secure ? "Secure" : "Insecure";

    try {
        if (secure) {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
        } else {
            tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
        }
    } catch (IOException | NullPointerException e) {
        Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
    }
    mmSocket = tmp;
    mState = STATE_CONNECTING;
}
 
Example 9
Project: Linphone4Android   File: BluetoothManager.java   Source Code and License 6 votes vote down vote up
public boolean isBluetoothHeadsetAvailable() {
	ensureInit();
	if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled() && mAudioManager != null && mAudioManager.isBluetoothScoAvailableOffCall()) {
		boolean isHeadsetConnected = false;
		if (mBluetoothHeadset != null) {
			List<BluetoothDevice> devices = mBluetoothHeadset.getConnectedDevices();
			mBluetoothDevice = null;
			for (final BluetoothDevice dev : devices) {    
				if (mBluetoothHeadset.getConnectionState(dev) == BluetoothHeadset.STATE_CONNECTED) {
					mBluetoothDevice = dev;
					isHeadsetConnected = true;
					break;
				}
			}
			Log.d(isHeadsetConnected ? "[Bluetooth] Headset found, bluetooth audio route available" : "[Bluetooth] No headset found, bluetooth audio route unavailable");
		}
		return isHeadsetConnected;
	}
	
	return false;
}
 
Example 10
Project: microbit   File: DfuBaseService.java   Source Code and License 6 votes vote down vote up
private boolean createBondApi18(final BluetoothDevice device) {
/*
 * There is a createBond() method in BluetoothDevice class but for now it's hidden. We will call it using reflections. It has been revealed in KitKat (Api19)
 */
      try {
          final Method createBond = device.getClass().getMethod("createBond");
          if (createBond != null) {
              sendLogBroadcast(LOG_LEVEL_DEBUG, "gatt.getDevice().createBond() (hidden)");
              return (Boolean) createBond.invoke(device);
          }
      } catch (final Exception e) {
          Log.w(TAG, "An exception occurred while creating bond", e);
          Log.e(TAG, e.toString());
      }

      return false;
  }
 
Example 11
Project: androidthings-bluetooth-pairing   File: MainActivity.java   Source Code and License 6 votes vote down vote up
private void unpairBondedDevices() {
    Log.d(TAG, "unpairBondedDevices");
    if (mBluetoothAdapter != null) {
        Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices();
        for (BluetoothDevice device : bondedDevices) {
            Log.d(TAG, "bonded device:" + device.getName());
            if (TARGET_DEVICE_NAME.contains(device.getName())) {
                unpairDevice(device);
            } else {
                Log.d(TAG, "it is not target device");
            }
        }
    } else {
        Log.d(TAG, "mBluetoothAdapter!=null");
    }
}
 
Example 12
Project: dab-iot   File: BluetoothChatService.java   Source Code and License 6 votes vote down vote up
/**
 * Start the ConnectThread to initiate a connection to a remote device.
 *
 * @param device The BluetoothDevice to connect
 * @param secure Socket Security type - Secure (true) , Insecure (false)
 */
public synchronized void connect(BluetoothDevice device, boolean secure) {
    Log.d(TAG, "connect to: " + device);

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

    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {
        mConnectedThread.cancel();
        mConnectedThread = null;
    }

    // Start the thread to connect with the given device
    mConnectThread = new ConnectThread(device, secure);
    mConnectThread.start();
    // Update UI title
    updateUserInterfaceTitle();
}
 
Example 13
Project: Blockly   File: ConnectBluetoothThread.java   Source Code and License 6 votes vote down vote up
public ConnectBluetoothThread(BluetoothDevice device, BluetoothAdapter mBluetoothAdapter, Handler handler) {
    // Use a temporary object that is later assigned to mmSocket,
    // because mmSocket is final
    this.mBluetoothAdapter=mBluetoothAdapter;
    this.handler=handler;
    mmDevice = device;

    BluetoothSocket tmp = null;
    msg=new Message();

    // Get a BluetoothSocket to connect with the given BluetoothDevice
    try {
        // MY_UUID is the app's UUID string, also used by the server code
        String uuid="00001101-0000-1000-8000-00805f9b34fb";
        tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(uuid));
    } catch (IOException e) {
        Log.d(TAG, "ConnectBluetoothThread: 初始化uuid错误");
    }
    mmSocket = tmp;
}
 
Example 14
Project: bluewatcher   File: WatchSelectorActivity.java   Source Code and License 6 votes vote down vote up
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    final BluetoothDevice device = devicesListAdapter.getDevice(position);
    if (device == null) return;
    
    if (scanningBleDevices) {
        bluetoothAdapter.stopLeScan(mLeScanCallback);
        scanningBleDevices = false;
    }
    
    final Intent intent = new Intent();
    intent.putExtra(EXTRAS_DEVICE_NAME, device.getName());
    intent.putExtra(EXTRAS_DEVICE_ADDRESS, device.getAddress());
    setResult(Activity.RESULT_OK, intent);
    finish();
}
 
Example 15
Project: phonk   File: PBluetoothClient.java   Source Code and License 6 votes vote down vote up
public ConnectedThread(BluetoothSocket socket, BluetoothDevice device) {
    MLog.d(TAG, "create ConnectedThread");
    mmSocket = socket;
    mmDevice = device;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;

    // Get the BluetoothSocket input and output streams
    try {
        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream();
    } catch (IOException e) {
        Log.e(TAG, "temp sockets not created", e);
    }

    mmInStream = tmpIn;
    mmOutStream = tmpOut;
}
 
Example 16
Project: Quick-Bluetooth-LE   File: MainActivity.java   Source Code and License 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
public void onDeviceFound(final BluetoothDevice device, int rssi, byte[] scanRecord) {
	runOnUiThread(new Runnable() {
		@Override
		public void run() {
			if (!deviceAddresses.contains(device.getAddress())) {
				deviceAddresses.add(device.getAddress());
				deviceList.add(device);
				String name = device.getName();
				if (name == null)
					name = "Unknown Device";
				deviceNames.add(name);
			}
		}
	});
}
 
Example 17
Project: Android-DFU-App   File: BleProfileService.java   Source Code and License 6 votes vote down vote up
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
	if (intent == null || !intent.hasExtra(EXTRA_DEVICE_ADDRESS))
		throw new UnsupportedOperationException("No device address at EXTRA_DEVICE_ADDRESS key");

	final Uri logUri = intent.getParcelableExtra(EXTRA_LOG_URI);
	mLogSession = Logger.openSession(getApplicationContext(), logUri);
	mDeviceAddress = intent.getStringExtra(EXTRA_DEVICE_ADDRESS);

	Logger.i(mLogSession, "Service started");

	// notify user about changing the state to CONNECTING
	final Intent broadcast = new Intent(BROADCAST_CONNECTION_STATE);
	broadcast.putExtra(EXTRA_CONNECTION_STATE, STATE_CONNECTING);
	LocalBroadcastManager.getInstance(BleProfileService.this).sendBroadcast(broadcast);

	final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
	final BluetoothAdapter adapter = bluetoothManager.getAdapter();
	final BluetoothDevice device = adapter.getRemoteDevice(mDeviceAddress);
	mDeviceName = device.getName();
	onServiceStarted();

	mBleManager.connect(device);
	return START_REDELIVER_INTENT;
}
 
Example 18
Project: Lazy-Switches   File: BluetoothService.java   Source Code and License 6 votes vote down vote up
public ConnectThread(BluetoothDevice device) {
    // Use a temporary object that is later assigned to mmSocket,
    // because mmSocket is final
    BluetoothSocket tmp = null;
    mmDevice = device;

    // Get a BluetoothSocket to connect with the given BluetoothDevice
    try {
        // MY_UUID is the app's UUID string, also used by the server code
        UUID uuid = Constants.myUUID;
        tmp = device.createRfcommSocketToServiceRecord(uuid);
    } catch (IOException e) {
        Log.e(Constants.TAG, "Create RFcomm socket failed", e);
    }
    mmSocket = tmp;
}
 
Example 19
Project: AndroidSDK2.0   File: DeviceListActivity.java   Source Code and License 6 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
    super.onScanResult(callbackType, result);
    BluetoothDevice device = result.getDevice();
    if ( device != null )
    {
        String msg = device.getName() + "\n" +"[RSSI : " + result.getRssi() + "dBm]" + device.getAddress();
        NLog.d( "onLeScan " + msg );

        /**
         * setting pen client control for ble
         */
            if(!temp.contains( device.getAddress() ))
            {
                NLog.d( "ACTION_FOUND onLeScan : " +device.getName() + " address : "+ device.getAddress()+", COD:" + device.getBluetoothClass());
                temp.add( device.getAddress());
                mNewDevicesArrayAdapter.add(msg);
            }
    }
}
 
Example 20
Project: Presenter-Client-Android   File: BluetoothPresenterControl.java   Source Code and License 6 votes vote down vote up
/**
 * Initiate the transmission using a given socket.
 *
 * @param socket The socket to connect to
 * @param control The parent remote control object
 * @param device The BluetoothDevice that has been connected
 */
ConnectedThread(BluetoothSocket socket, RemoteControl control, BluetoothDevice device) {
    mSocket = socket;
    mRemoteControl = control;
    mDevice = device;
    mMessageBuffer = new StringBuffer();
    InputStream tmpIn = null;
    OutputStream tmpOut = null;

    // Get the BluetoothSocket input and output streams
    try {
        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream();
    } catch (IOException e) {
        Log.e(TAG, "temp sockets not created", e);
    }

    mInStream = tmpIn;
    mOutStream = tmpOut;
    // State will be set to connected once the version information is exchanged and we
    // found a common protocol version set to use.
}
 
Example 21
Project: GodotBluetooth   File: GodotBluetooth.java   Source Code and License 6 votes vote down vote up
/**
 * Organizes and sends to Godot all external paired devices
 */

private void listPairedDevices() {

    String localDeviceName = localBluetooth.getName();
    String localDeviceAddress = localBluetooth.getAddress();

    Set<BluetoothDevice> pairedDevices = localBluetooth.getBondedDevices();

    if(pairedDevices.size() > 0) {
        pairedDevicesAvailable = (Object []) pairedDevices.toArray();
        int externalDeviceID = 0;

        for (BluetoothDevice device : pairedDevices) {
            String externalDeviceName = device.getName();
            String externalDeviceAddress = device.getAddress();

            GodotLib.calldeferred(instanceId, "_on_single_device_found", new Object[]{ externalDeviceName, externalDeviceAddress, externalDeviceID });
            externalDeviceID += 1;
        }

        pairedDevicesListed = true;
    }
}
 
Example 22
Project: Android-DFU-App   File: BleManager.java   Source Code and License 6 votes vote down vote up
/**
 * When the device is bonded and has the Generic Attribute service and the Service Changed characteristic this method enables indications on this characteristic.
 * In case one of the requirements is not fulfilled this method returns <code>false</code>.
 *
 * @param gatt the gatt device with services discovered
 * @return <code>true</code> when the request has been sent, <code>false</code> when the device is not bonded, does not have the Generic Attribute service, the GA service does not have
 * the Service Changed characteristic or this characteristic does not have the CCCD.
 */
private boolean ensureServiceChangedEnabled(final BluetoothGatt gatt) {
	if (gatt == null)
		return false;

	// The Service Changed indications have sense only on bonded devices
	final BluetoothDevice device = gatt.getDevice();
	if (device.getBondState() != BluetoothDevice.BOND_BONDED)
		return false;

	final BluetoothGattService gaService = gatt.getService(GENERIC_ATTRIBUTE_SERVICE);
	if (gaService == null)
		return false;

	final BluetoothGattCharacteristic scCharacteristic = gaService.getCharacteristic(SERVICE_CHANGED_CHARACTERISTIC);
	if (scCharacteristic == null)
		return false;

	Logger.i(mLogSession, "Service Changed characteristic found on a bonded device");
	return enableIndications(scCharacteristic);
}
 
Example 23
Project: MobileAppForPatient   File: SearchMeterDialog.java   Source Code and License 6 votes vote down vote up
public View getView(final int position, View convertView, ViewGroup parent) {
 		
 		ViewHolder viewHolder = null;
 		View vi = convertView;
 		if(convertView == null) {
 			vi = inflater.inflate(R.layout.listview_content_search, null);
 			viewHolder = new ViewHolder();
 			viewHolder.tvTitle = (TextView) vi.findViewById(R.id.tv_title);
 			viewHolder.btnDel = (Button) vi.findViewById(R.id.btn_del);
 			vi.setTag(viewHolder);
 		}
 		else {
 			viewHolder = (ViewHolder) convertView.getTag();
 		}
 		
 		viewHolder.tvTitle.setText(mSearchedDevices.get(position).getName().toString());
 		viewHolder.btnDel.setOnClickListener(new View.OnClickListener() {
	
	@Override
	public void onClick(View v) {
		BluetoothDevice searchedDevice = mSearchedDevices.get(position);
		String macAddress = searchedDevice.getAddress();
   		if (!(macAddress.equals("N/A") || TextUtils.isEmpty(macAddress))) {
   			if (mHandler != null) {
   				mHandler.OnSearchBLEClicked(searchedDevice);
   			}
           }
           
           dismiss();
	}
});
 		
 		return vi;
 	}
 
Example 24
Project: Pc-Control   File: BluetoothDevicesActivity.java   Source Code and License 6 votes vote down vote up
public void onReceive(Context context, Intent intent)
{
	String action = intent.getAction();
	
	if (action.equals(BluetoothDevice.ACTION_FOUND))
	{
		BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
		
		if (!BluetoothDevicesActivity.this.deviceList.contains(device))
		{
			BluetoothDevicesActivity.this.deviceList.add(device);
			BluetoothDevicesActivity.this.deviceListAdapter.notifyDataSetChanged();
		}
	}
	else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED))
	{
		Toast.makeText(context, "Bluetooth discovery started", Toast.LENGTH_SHORT).show();

	}
	else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED))
	{
		Toast.makeText(context, "Bluetooth discovery finished", Toast.LENGTH_SHORT).show();

	}
}
 
Example 25
Project: TrainAppTFG   File: BluetoothLeService.java   Source Code and License 6 votes vote down vote up
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
        Log.d("BLUETOOTH", "DISCOVERY STARTED"); //lo que se ejecuta cuando el bluetooth comienza a escanear
    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { //lo que se ejecuta cuando el bluetooth finaliza el escaneo
        Log.d("BLUETOOTH", "DISCOVERY FINISHED");

    } else if (BluetoothDevice.ACTION_FOUND.equals(action)) { //lo que se ejecuta cuando el bluetooth encuentra un dispositivo
        final BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        Log.d("BLUETOOTH", "DEVICE DISCOVERED");

        listaDevices.put(device.getAddress(), device);
        Bundle bundle = new Bundle();
        bundle.putString("address", device.getAddress());
        //TODO crear constantes para los codigos de envio
        resultReceiverListarYConectar.send(100, bundle);
        /*runOnUiThread(new Runnable() {
            @Override
            public void run() {
                list.add(device.getAddress());
                listaDevices.put(device.getAddress(), device);
                adapter.notifyDataSetChanged();
            }
        });*/
    }
}
 
Example 26
Project: AndroidMuseumBleManager   File: BluetoothLeScannerCompat.java   Source Code and License 6 votes vote down vote up
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
    ScanCallbackCompat callbackCompat = callbackCompatRef.get();
    if (callbackCompat == null) return;

    ScanResultCompat result = new ScanResultCompat(
            device,
            ScanRecordCompat.parseFromBytes(scanRecord),
            rssi, System.currentTimeMillis());

    // No filters so return any result
    if (filters == null) {
        callbackCompat.onScanResult(ScanSettingsCompat.CALLBACK_TYPE_ALL_MATCHES, result);
        return;
    }

    // Filters specified, so see if there is a match.
    for (ScanFilterCompat filter : filters) {
        if (filter.matches(result)) {
            callbackCompat.onScanResult(ScanSettingsCompat.CALLBACK_TYPE_ALL_MATCHES, result);
            return;
        }
    }
}
 
Example 27
Project: MobileAppForPatient   File: BluetoothHandler.java   Source Code and License 6 votes vote down vote up
/**
 * connect the device to bluetooth
 *
 * @param context    the context
 * @param deviceInfo the device info
 * @param receiver   the receiver
 * @throws DeviceConnectException the device connect exception
 */
public void connectToBluetooth(Context context, DeviceInfoBean deviceInfo, IHealthCareReceiver receiver) throws DeviceConnectException {
    isDeviceFound = false;
    iHealthCareReceiver = receiver;
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
        throw new DeviceConnectException(mContext.getString(R.string.bluetooth_settings_problem));
    }

    mContext = context;
    mDeviceInfo = deviceInfo;
    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    mContext.getApplicationContext().registerReceiver(mReceiver, filter);

    if (mBluetoothAdapter.getState() != BluetoothAdapter.STATE_ON)
        throw new DeviceConnectException(mContext.getString(R.string.bluetooth_state_not_ready));

    mBluetoothAdapter.startDiscovery();
}
 
Example 28
Project: Obd2-Tracker   File: ObdBluetoothService.java   Source Code and License 5 votes vote down vote up
private BluetoothSocket startBluetoothConnection(BluetoothDevice bluetoothDevice) throws IOException {
    log.debug("Starting OBD connection..");
    isRunning = true;
    BluetoothSocket bluetoothSocket = null;
    try {
        bluetoothSocket = BluetoothManager.connect(bluetoothDevice);
    } catch (Exception e2) {
        log.error("There was an error while establishing Bluetooth connection. Stopping app..", e2);
        stopService();
        throw new IOException();
    }

    return bluetoothSocket;
}
 
Example 29
Project: journey-android-bluetooth-scale   File: BluetoothService.java   Source Code and License 5 votes vote down vote up
public final synchronized void connectToDevice(BluetoothDevice bluetoothDevice) {
    Log.i(TAG, "BluetoothService connectToDevice " + bluetoothDevice.toString());
    this.close();
    this.bluetoothServiceThread = new BluetoothServiceThread(this, bluetoothDevice);
    this.bluetoothServiceThread.start();
    setState(ConnectionState.CONNECTING);
}
 
Example 30
Project: Android-DFU-App   File: BleProfileServiceReadyActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onDeviceSelected(final BluetoothDevice device, final String name) {
	final int titleId = getLoggerProfileTitle();
	if (titleId > 0) {
		mLogSession = Logger.newSession(getApplicationContext(), getString(titleId), device.getAddress(), name);
		// If nRF Logger is not installed we may want to use local logger
		if (mLogSession == null && getLocalAuthorityLogger() != null) {
			mLogSession = LocalLogSession.newSession(getApplicationContext(), getLocalAuthorityLogger(), device.getAddress(), name);
		}
	}
	mDeviceName = name;
	mDeviceNameView.setText(name != null ? name : getString(R.string.not_available));
	mConnectButton.setText(R.string.action_disconnect);

	// The device may not be in the range but the service will try to connect to it if it reach it
	Logger.d(mLogSession, "Creating service...");
	final Intent service = new Intent(this, getServiceClass());
	service.putExtra(BleProfileService.EXTRA_DEVICE_ADDRESS, device.getAddress());
	if (mLogSession != null)
		service.putExtra(BleProfileService.EXTRA_LOG_URI, mLogSession.getSessionUri());
	startService(service);
	Logger.d(mLogSession, "Binding to the service...");
	bindService(service, mServiceConnection, 0);
}
 
Example 31
Project: mDL-ILP   File: GattService.java   Source Code and License 5 votes vote down vote up
@Override
public synchronized void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
    dataWaiting = false;

    apduCharacteristic.setValue(apduRecvStream.toByteArray());
    apduRecvStream = null;

    gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, null);

    writeReceived = true;
    notifyAll();
}
 
Example 32
Project: noise   File: BluetoothSyncService.java   Source Code and License 5 votes vote down vote up
public BluetoothClassicClient(BluetoothDevice device, UUID uuid) {
    macAddress = device.getAddress();
    try {
        socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
    } catch (IOException connectException) {
        Log.e(TAG, "Failed to set up a Bluetooth Classic connection as a client", connectException);
    }
}
 
Example 33
Project: BluetoothKit   File: BeaconDevice.java   Source Code and License 5 votes vote down vote up
/**
 * 更新当前设备的信息
 *
 * @param bluetoothDevice
 * @param rssi
 * @param scanRecord
 * @param lastUpdatedTimeMillis
 */
public void updateDevice(@NonNull BluetoothDevice bluetoothDevice, int rssi, @NonNull byte[] scanRecord, long lastUpdatedTimeMillis) {
    this.bluetoothDevice = bluetoothDevice;
    this.rssi = rssi;
    this.scanRecord = scanRecord;

    this.lastUpdatedTimeMillis = lastUpdatedTimeMillis;

    this.createIBeacon();
}
 
Example 34
Project: buildAPKsSamples   File: BluetoothChatService.java   Source Code and License 5 votes vote down vote up
/**
 * Start the ConnectedThread to begin managing a Bluetooth connection
 * @param socket  The BluetoothSocket on which the connection was made
 * @param device  The BluetoothDevice that has been connected
 */
public synchronized void connected(BluetoothSocket socket, BluetoothDevice
        device, final String socketType) {
    if (D) Log.d(TAG, "connected, Socket Type:" + socketType);

    // Cancel the thread that completed the connection
    if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

    // Cancel the accept thread because we only want to connect to one device
    if (mSecureAcceptThread != null) {
        mSecureAcceptThread.cancel();
        mSecureAcceptThread = null;
    }
    if (mInsecureAcceptThread != null) {
        mInsecureAcceptThread.cancel();
        mInsecureAcceptThread = null;
    }

    // Start the thread to manage the connection and perform transmissions
    mConnectedThread = new ConnectedThread(socket, socketType);
    mConnectedThread.start();

    // Send the name of the connected device back to the UI Activity
    Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
    Bundle bundle = new Bundle();
    bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());
    msg.setData(bundle);
    mHandler.sendMessage(msg);

    setState(STATE_CONNECTED);
}
 
Example 35
Project: LittleBitLouder   File: BluetoothReceiver.java   Source Code and License 5 votes vote down vote up
public boolean foundDevice (BluetoothDevice device)
{
    boolean resultIsNew = false;

    if (device != null && device.getName() != null &&
            (device.getBluetoothClass().getDeviceClass() == BluetoothClass.Device.COMPUTER_HANDHELD_PC_PDA ||
                    device.getBluetoothClass().getDeviceClass() == BluetoothClass.Device.COMPUTER_PALM_SIZE_PC_PDA ||
                    device.getBluetoothClass().getDeviceClass() == BluetoothClass.Device.PHONE_SMART)) {


        if (mPairedDevicesOnly && device.getBondState() == BluetoothDevice.BOND_NONE)
            return false; //we can only support paired devices


        if (!mFoundDevices.containsKey(device.getAddress())) {
            mFoundDevices.put(device.getAddress(), device);
            resultIsNew = true;

            if (mNearbyListener != null) {
                Neighbor neighbor = new Neighbor(device.getAddress(),device.getName(),Neighbor.TYPE_BLUETOOTH);
                mNearbyListener.foundNeighbor(neighbor);
            }
        }

        if (clientThreads.containsKey(device.getAddress()))
            if (clientThreads.get(device.getAddress()).isAlive())
                return false; //we have a running thread here people!

        log("Found device: " + device.getName() + ":" + device.getAddress());

        ClientThread clientThread = new ClientThread(device, mHandler, mPairedDevicesOnly);
        clientThread.start();

        clientThreads.put(device.getAddress(), clientThread);

    }

    return resultIsNew;
}
 
Example 36
Project: AndroidBleWrapper   File: BleWrapper.java   Source Code and License 5 votes vote down vote up
private BluetoothDevice getBluetoothDevice(Context context, String deviceAddress) {
  BluetoothManager bluetoothManager = (BluetoothManager) context
      .getSystemService(Context.BLUETOOTH_SERVICE);
  BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
  return bluetoothAdapter.getRemoteDevice(deviceAddress);
}
 
Example 37
Project: thermalprinterhelper   File: PrinterListPresenter.java   Source Code and License 5 votes vote down vote up
private void saveDeviceInfo(BluetoothDevice device){
    SharedPreferences.Editor prefEditor = preferences.edit();
    prefEditor.putString(mActivity.getString(R.string.pref_general_printer), device==null?"":device.getName());
    prefEditor.putString(mActivity.getString(R.string.pref_general_printer_address), device==null?"":device.getAddress());
    prefEditor.commit();
    getView().refreshAdapter();
}
 
Example 38
Project: UnityBluetoothPlugin   File: BluetoothPlugin.java   Source Code and License 5 votes vote down vote up
@RequiresPermission(
        allOf = {"android.permission.BLUETOOTH", "android.permission.BLUETOOTH_ADMIN"}
)
public void Connect(String TheAdrees) {
    if(this.mBtAdapter.isDiscovering()) {
        this.mBtAdapter.cancelDiscovery();
    }

    this.IsScan = false;
    String address = TheAdrees.substring(TheAdrees.length() - 17);
    this.mConnectedDeviceName = TheAdrees.split(",")[0];
    BluetoothDevice device = this.mBtAdapter.getRemoteDevice(address);

    this.mBtService.connect(device);
}
 
Example 39
Project: xlight_android_native   File: ClsUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 与设备解除配对 参考源码:platform/packages/apps/Settings.git
 * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
 */
static public boolean removeBond(Class btClass, BluetoothDevice btDevice)
        throws Exception {
    Method removeBondMethod = btClass.getMethod("removeBond");
    Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
    return returnValue.booleanValue();
}
 
Example 40
Project: bluewatcher   File: WatchSelectorActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
	runOnUiThread(new Runnable() {
		@Override
		public void run() {
			devicesListAdapter.addDevice(device);
			devicesListAdapter.notifyDataSetChanged();
		}
	});
}
 
Example 41
Project: UnityBluetoothPlugin   File: BluetoothService.java   Source Code and License 5 votes vote down vote up
public ConnectThread(BluetoothDevice device) {
    this.mmDevice = device;
    BluetoothSocket tmp = null;

    try {
        tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) {
        Log.e(TAG, "create() failed", e);
    }
    mmSocket = tmp;
}
 
Example 42
Project: bluewatcher   File: BluetoothClientService.java   Source Code and License 5 votes vote down vote up
private boolean isConnected(BluetoothDevice device) {
	List<BluetoothDevice> connectedDevices = ((BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE)).getConnectedDevices(7);
	for(BluetoothDevice d : connectedDevices) {
		Log.d(TAG, "Connected device: " + d.getName());
	}
	return connectedDevices.contains(device);
}
 
Example 43
Project: Android-DFU-App   File: BleManager.java   Source Code and License 5 votes vote down vote up
@Override
public final void onDescriptorWrite(final BluetoothGatt gatt, final BluetoothGattDescriptor descriptor, final int status) {
	if (status == BluetoothGatt.GATT_SUCCESS) {
		Logger.i(mLogSession, "Data written to descr. " + descriptor.getUuid() + ", value: " + ParserUtils.parse(descriptor));

		if (isServiceChangedCCCD(descriptor)) {
			Logger.a(mLogSession, "Service Changed notifications enabled");
			if (!readBatteryLevel())
				nextRequest();
		} else if (isBatteryLevelCCCD(descriptor)) {
			final byte[] value = descriptor.getValue();
			if (value != null && value.length > 0 && value[0] == 0x01) {
				Logger.a(mLogSession, "Battery Level notifications enabled");
				nextRequest();
			} else
				Logger.a(mLogSession, "Battery Level notifications disabled");
		} else {
			nextRequest();
		}
	} else if (status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) {
		if (gatt.getDevice().getBondState() != BluetoothDevice.BOND_NONE) {
			DebugLogger.w(TAG, ERROR_AUTH_ERROR_WHILE_BONDED);
			mCallbacks.onError(ERROR_AUTH_ERROR_WHILE_BONDED, status);
		}
	} else {
		DebugLogger.e(TAG, "onDescriptorWrite error " + status);
		onError(ERROR_WRITE_DESCRIPTOR, status);
	}
}
 
Example 44
Project: BluetoothStudy   File: DeviceListFragment.java   Source Code and License 5 votes vote down vote up
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
        convertView = getActivity().getLayoutInflater().inflate(R.layout.layout_item_bt_device, parent, false);
        viewHolder = new ViewHolder();
        viewHolder.deviceName = (TextView) convertView.findViewById(R.id.device_name);
        viewHolder.deviceMac = (TextView) convertView.findViewById(R.id.device_mac);
        viewHolder.deviceState = (TextView) convertView.findViewById(R.id.device_state);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }
    int code = deviceList.get(position).getBondState();
    String name = deviceList.get(position).getName();
    String mac = deviceList.get(position).getAddress();
    String state;
    if (name == null || name.length() == 0) {
        name = "未命名设备";
    }
    if (code == BluetoothDevice.BOND_BONDED) {
        state = "ready";
        viewHolder.deviceState.setTextColor(getResources().getColor(R.color.green));
    } else {
        state = "new";
        viewHolder.deviceState.setTextColor(getResources().getColor(R.color.red));
    }
    if (mac == null || mac.length() == 0) {
        mac = "未知 mac 地址";
    }
    viewHolder.deviceName.setText(name);
    viewHolder.deviceMac.setText(mac);
    viewHolder.deviceState.setText(state);
    return convertView;
}
 
Example 45
Project: BluetoothKit   File: BeaconDevice.java   Source Code and License 5 votes vote down vote up
public BeaconDevice(@NonNull BluetoothDevice bluetoothDevice, int rssi, @NonNull byte[] scanRecord, long lastUpdatedTimeMillis, boolean createIBeacon) {
    this.bluetoothDevice = bluetoothDevice;
    this.rssi = rssi;
    this.scanRecord = scanRecord;

    this.lastUpdatedTimeMillis = lastUpdatedTimeMillis;

    if (createIBeacon) {
        this.createIBeacon();
    }
}
 
Example 46
Project: bluetooth-scanner   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void scanBluetooth() {
    bluetoothReceiverRegistered = true;
    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(bluetoothReceiver, filter);
    if (mBluetoothAdapter.isDiscovering()) {
        mBluetoothAdapter.cancelDiscovery();
    }
    mBluetoothAdapter.startDiscovery();
}
 
Example 47
Project: sample-bluetooth-audio   File: A2dpSinkActivity.java   Source Code and License 5 votes vote down vote up
private void disconnectConnectedDevices() {
    if (mA2DPSinkProxy == null || mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        return;
    }
    speak("Disconnecting devices");
    for (BluetoothDevice device: mA2DPSinkProxy.getConnectedDevices()) {
        Log.i(TAG, "Disconnecting device " + device);
        A2dpSinkHelper.disconnect(mA2DPSinkProxy, device);
    }
}
 
Example 48
Project: synesthesiavision   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
        //If bluetooth is disconnected then interrupt the socket and init the ConnectBluetooth activity
        ConnectBluetooth.btt.interrupt();
        Toast.makeText(getApplicationContext(), "BT Disconnected", Toast.LENGTH_SHORT).show();
    }
}
 
Example 49
Project: VR-One   File: MainActivity.java   Source Code and License 5 votes vote down vote up
/**
 * Establish connection with other device
 *
 * @param secure Socket Security type - Secure (true) , Insecure (false)
 */
private void connectDevice(boolean secure) {
    // Get the device MAC address
    String address = mMacAddress;
    // Get the BluetoothDevice object
    //BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    BluetoothDevice device = mBluetoothDevice;
    // Attempt to connect to the device
    mBluetoothListener.connect(device, secure);
}
 
Example 50
Project: BluetoothChatDemo   File: ClientActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();
    if (mBlthChatUtil != null) {
        if (mBlthChatUtil.getState() == BluetoothChatUtil.STATE_CONNECTED) {
            BluetoothDevice device = mBlthChatUtil.getConnectedDevice();
            if (null != device && null != device.getName()) {
                mBtConnectState.setText("已成功连接到设备" + device.getName());
            } else {
                mBtConnectState.setText("已成功连接到设备");
            }
        }
    }
}
 
Example 51
Project: blue-pair   File: BluetoothController.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the name of a device. If the device name is not available, returns the device address.
 *
 * @param device the device whose name to return.
 * @return the name of the device or its address if the name is not available.
 */
public static String getDeviceName(BluetoothDevice device) {
    String deviceName = device.getName();
    if (deviceName == null) {
        deviceName = device.getAddress();
    }
    return deviceName;
}
 
Example 52
Project: thermalprinterhelper   File: PrinterListPresenter.java   Source Code and License 5 votes vote down vote up
public void unpairDialog(final BluetoothDevice device) {
    UtilsDialog.createAlertDialog(mActivity)
            .setTitle(mActivity.getString(R.string.printerlist_title))
            .setMessage(mActivity.getString(R.string.unsyncbluetooth))
            .setPositiveButton(mActivity.getString(R.string.yes), new DialogInterface.OnClickListener(){
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    unpairDevice(device);
                    dialog.dismiss();
                }
            })
            .setNegativeButton(mActivity.getString(R.string.cancel), null)
            .show();
}
 
Example 53
Project: BluetoothChatDemo   File: BluetoothChatUtil.java   Source Code and License 5 votes vote down vote up
public ConnectThread(BluetoothDevice device) {
    mmDevice = device;
    BluetoothSocket tmp = null;
    // 得到一个bluetoothsocket
    try {
        mmSocket = device.createRfcommSocketToServiceRecord
                (SERVICE_UUID);
    } catch (IOException e) {
        Log.e(TAG, "create() failed", e);
        mmSocket = null;
    }
}
 
Example 54
Project: AndroidSDK2.0   File: BTAdt.java   Source Code and License 5 votes vote down vote up
/**
 * Instantiates a new Connect thread.
 *
 * @param device the device
 */
public ConnectThread( BluetoothDevice device )
{
	mmDevice = device;

	BluetoothSocket tmp = null;
	if(mmDevice.getBluetoothClass() == null)
		mProtocolVer = 1;
	else if(mmDevice.getBluetoothClass().toString().equals( "51c") || mmDevice.getBluetoothClass().toString().equals( "2510"))
		mProtocolVer = 2;
	else
		mProtocolVer = 1;

	try
	{
		if(mProtocolVer == 2 && Build.VERSION.SDK_INT >= 19)
			tmp = device.createRfcommSocketToServiceRecord( NeoOne_UUID );
		else
			tmp = device.createInsecureRfcommSocketToServiceRecord( NeoOne_UUID );


	}
	catch ( Exception e )
	{
		NLog.e( "[BTAdt/ConnectThread] Socket Type : create() failed", e );
	}

	mmSocket = tmp;
}
 
Example 55
Project: Android-DFU-App   File: ProximityManager.java   Source Code and License 5 votes vote down vote up
@Override
public void onExecuteWrite(final BluetoothDevice device, final int requestId, final boolean execute) {
	Logger.d(mLogSession, "[Server callback] Execute write request (requestId=" + requestId + ", execute=" + execute + ")");
	// This method is not supported
	Logger.w(mLogSession, "[Server] Operation not supported");
	Logger.d(mLogSession, "[Server] server.sendResponse(GATT_REQUEST_NOT_SUPPORTED)");
	mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED, 0, null);
	Logger.v(mLogSession, "[Server] Response sent");
}
 
Example 56
Project: iconsole-android   File: BluetoothChatService.java   Source Code and License 5 votes vote down vote up
/**
 * Start the ConnectedThread to begin managing a Bluetooth connection
 *
 * @param socket The BluetoothSocket on which the connection was made
 * @param device The BluetoothDevice that has been connected
 */
public synchronized void connected(BluetoothSocket socket, BluetoothDevice
        device) {
    Log.d(TAG, "connected");

    // Cancel the thread that completed the connection
    if (mConnectThread != null) {
        mConnectThread.cancel();
        mConnectThread = null;
    }

    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {
        mConnectedThread.cancel();
        mConnectedThread = null;
    }

    // Start the thread to manage the connection and perform transmissions
    mConnectedThread = new ConnectedThread(socket);
    mConnectedThread.start();
    // Send the name of the connected device back to the UI Activity
    Message msg = mHandler.obtainMessage(Constants.MESSAGE_DEVICE_NAME);
    Bundle bundle = new Bundle();
    bundle.putString(Constants.DEVICE_NAME, device.getName());
    msg.setData(bundle);
    mHandler.sendMessage(msg);
    // Update UI title
    updateUserInterfaceTitle();
}
 
Example 57
Project: igrow-android   File: BluetoothLeScanL18Proxy.java   Source Code and License 5 votes vote down vote up
@Override
public void onLeScan(final BluetoothDevice device, int rssi,
                     byte[] scanRecord) {

    Log.d(TAG, String.format("RSSI: %d Found: %s Scan Record: %s",
            rssi, device.toString(), scanRecord.toString()));

    EnvironmentalSensorBLEScanUpdate sensorScanUpdate = new EnvironmentalSensorBLEScanUpdate(device.getAddress(), rssi);
    if (mCallback != null) {
        mCallback.onUpdate(sensorScanUpdate);
    }
}
 
Example 58
Project: thermalprinterhelper   File: PrinterListPresenter.java   Source Code and License 5 votes vote down vote up
private void unpairDevice(final BluetoothDevice device){
    try {
        Method method = device.getClass().getMethod("removeBond", (Class[]) null);
        method.invoke(device, (Object[]) null);

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 59
Project: Presenter-Client-Android   File: BluetoothPresenterControlTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test that disconnection from server is properly recognized while connection is still
 * establishing and initial information is not exchanged (e.g. version information).
 */
@Test
public void testServerDisconnectedDuringInformationExchange() throws InterruptedException {
    control = new BluetoothPresenterControl(new Handler() {});
    BluetoothDevice bluetoothDevice = ShadowBluetoothAdapter.getDefaultAdapter()
            .getRemoteDevice(DEVICE_ADDRESS);
    control.connect(bluetoothDevice);
    waitForServiceStateChanged(control, RemoteControl.ServiceState.CONNECTING);

    ShadowBluetoothSocket.setFailReading(true);
    // Wait some time until the thread really stopped
    waitForServiceStateChanged(control, RemoteControl.ServiceState.NONE);
}
 
Example 60
Project: android-robocar   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void setupBluetooth() {
  nes30Manager = new Nes30Manager(this);
  nes30Connection = new Nes30Connection(this, RobocarConstants.NES30_MAC_ADDRESS);
  Timber.d("BT status: %b", nes30Connection.isEnabled());
  Timber.d("Paired devices: %d", nes30Connection.getPairedDevices().size());

  BluetoothDevice nes30device = nes30Connection.getSelectedDevice();
  if (nes30device == null) {
    Timber.d("Starting discovery: %b", nes30Connection.startDiscovery());
  } else {
    Timber.d("Creating bond: %b", nes30Connection.createBond(nes30device));
  }
}