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!"); }
@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); } } }
@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); } }
@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()); } }
@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; }
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; }
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; }
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; }
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"); } }
/** * 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(); }
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; }
@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(); }
@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); }
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; }
@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); } } }); }
@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; }
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; }
@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); } } }
/** * 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. }
/** * 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; } }
/** * 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); }
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; }
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(); } }
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(); } });*/ } }
@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; } } }
/** * 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(); }
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; }
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); }
@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); }
@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(); }
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); } }
/** * 更新当前设备的信息 * * @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(); }
/** * 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); }
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; }
private BluetoothDevice getBluetoothDevice(Context context, String deviceAddress) { BluetoothManager bluetoothManager = (BluetoothManager) context .getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter(); return bluetoothAdapter.getRemoteDevice(deviceAddress); }
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(); }
@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); }
/** * 与设备解除配对 参考源码: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(); }
@Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) { runOnUiThread(new Runnable() { @Override public void run() { devicesListAdapter.addDevice(device); devicesListAdapter.notifyDataSetChanged(); } }); }