List of usage examples for android.bluetooth BluetoothDevice getName
@RequiresPermission(Manifest.permission.BLUETOOTH)
public String getName()
From source file:com.filterdevice.ProfileScanningFragment.java
/** * Method to connect to the device selected. The time allotted for having a * connection is 8 seconds. After 8 seconds it will disconnect if not * connected and initiate scan once more * * @param device//from w ww . ja v a2 s .c o m */ private void connectDevice(BluetoothDevice device, boolean isFirstConnect) { mDeviceAddress = device.getAddress(); mDeviceName = device.getName(); // Get the connection status of the device if (bluetoothLeService.getConnectionState() == bluetoothLeService.STATE_DISCONNECTED) { Logger.v("BLE DISCONNECTED STATE"); // Disconnected,so connect bluetoothLeService.connect(mDeviceAddress); showConnectAlertMessage(mDeviceName, mDeviceAddress); } else { Logger.v("BLE OTHER STATE-->" + bluetoothLeService.getConnectionState()); // Connecting to some devices,so disconnect and then connect bluetoothLeService.disconnect(); Handler delayHandler = new Handler(); delayHandler.postDelayed(new Runnable() { @Override public void run() { bluetoothLeService.connect(mDeviceAddress); showConnectAlertMessage(mDeviceName, mDeviceAddress); } }, DELAY_PERIOD); } if (isFirstConnect) { startConnectTimer(); mConnectTimerON = true; } }
From source file:com.android.tv.settings.MainFragment.java
private void updateAccessories() { if (mAccessoriesGroup == null) { return;// w w w .j a va2 s .co m } if (mBtAdapter == null) { mAccessoriesGroup.setVisible(false); mAccessoriesGroup.removeAll(); return; } final Set<BluetoothDevice> bondedDevices = mBtAdapter.getBondedDevices(); final Set<String> connectedBluetoothAddresses = BluetoothConnectionsManager.getConnectedSet(getContext()); final Context themedContext = getPreferenceManager().getContext(); final Set<String> touchedKeys = new ArraySet<>(bondedDevices.size() + 1); if (mAddAccessory != null) { touchedKeys.add(mAddAccessory.getKey()); } for (final BluetoothDevice device : bondedDevices) { final String desc = connectedBluetoothAddresses.contains(device.getAddress()) ? getString(R.string.accessory_connected) : null; final String key = "BluetoothDevice:" + device.getAddress(); touchedKeys.add(key); Preference preference = mAccessoriesGroup.findPreference(key); if (preference == null) { preference = new Preference(themedContext); preference.setKey(key); } preference.setTitle(device.getName()); preference.setSummary(desc); final int deviceImgId = AccessoryUtils.getImageIdForDevice(device); preference.setIcon(deviceImgId); preference.setFragment(BluetoothAccessoryFragment.class.getName()); BluetoothAccessoryFragment.prepareArgs(preference.getExtras(), device.getAddress(), device.getName(), deviceImgId); mAccessoriesGroup.addPreference(preference); } for (int i = 0; i < mAccessoriesGroup.getPreferenceCount();) { final Preference preference = mAccessoriesGroup.getPreference(i); if (touchedKeys.contains(preference.getKey())) { i++; } else { mAccessoriesGroup.removePreference(preference); } } }
From source file:org.thecongers.mtpms.MainActivity.java
private boolean btConnect() { btAdapter = BluetoothAdapter.getDefaultAdapter(); checkBTState();/*from ww w . j a v a 2 s . c o m*/ if (btAdapter != null) { Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices(); // If there are paired devices if (pairedDevices.size() > 0) { // Loop through paired devices for (BluetoothDevice device : pairedDevices) { if (device.getName().contains("iTPMS")) { address = device.getAddress(); Log.d(TAG, "Paired iTPMSystem found: " + device.getName() + " " + device.getAddress()); } } if (address == null) { Toast.makeText(MainActivity.this, getResources().getString(R.string.toast_noPaired), Toast.LENGTH_LONG).show(); return false; } } if (address != null) { // Set up a pointer to the remote node using it's address. BluetoothDevice device = btAdapter.getRemoteDevice(address); btConnectThread = new ConnectThread(device); btConnectThread.start(); } else { Toast.makeText(MainActivity.this, getResources().getString(R.string.toast_noPaired), Toast.LENGTH_LONG).show(); return false; } return true; } Log.d(TAG, "Bluetooth not supported"); return false; }
From source file:com.cognizant.glass.bluetoothconnect.DemoAppRecieverService.java
/** * Start the ConnectedThread to begin managing a Bluetooth connection * // w w w . j a va2 s . c o m * @param socket * The BluetoothSocket on which the connection was made * @param device * The BluetoothDevice that has been connected */ public synchronized void connected(final BluetoothSocket socket, BluetoothDevice device) { if (D) Log.d(TAG, "connected"); // Start the thread to manage the connection and perform transmissions mConnectedThread = new ConnectedThread(socket); mConnectedThread.start(); // Add each connected thread to an array mConnThreads.add(mConnectedThread); // Send the name of the connected device back to the UI Activity final Message msg = mHandler.obtainMessage(MESSAGE_DEVICE_NAME); Bundle bundle = new Bundle(); bundle.putString(Constants.DEVICENAME, device.getName()); msg.setData(bundle); mHandler.sendMessage(msg); }
From source file:com.elitise.appv2.Peripheral.java
private void disconnectFromDevices() { Log.d(TAG, "Disconnecting devices..."); for (BluetoothDevice device : mBluetoothManager.getConnectedDevices(BluetoothGattServer.GATT)) { Log.d(TAG, "Devices: " + device.getAddress() + " " + device.getName()); mGattServer.cancelConnection(device); //mGattServer.close(); }/* w w w. j ava2s. c o m*/ }
From source file:org.apache.cordova.plugin.BluetoothPlugin2.java
@Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { logDbg("Action: " + action); if (ACTION_IS_SUPPORTED.equals(action)) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, m_bluetoothAdapter != null)); return true; } else if (m_bluetoothAdapter == null) { String msg = "Bluetooth is not supported !"; callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, msg)); logErr(msg);/*from ww w . j ava2 s . c om*/ return true; } else if (ACTION_ENABLE.equals(action)) { this.callback_enable = callbackContext; PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); if (!m_bluetoothAdapter.isEnabled()) { this.cordova.startActivityForResult(this, new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), this.REQUEST_CODE_ENABLE); } callbackContext.sendPluginResult(pluginResult); return true; } else if (ACTION_DISABLE.equals(action)) { PluginResult pluginResult; if (!m_bluetoothAdapter.disable() && !(m_bluetoothAdapter.getState() == BluetoothAdapter.STATE_TURNING_OFF || m_bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF)) { pluginResult = new PluginResult(PluginResult.Status.ERROR); } else { pluginResult = new PluginResult(PluginResult.Status.OK); } callbackContext.sendPluginResult(pluginResult); return true; } else if (ACTION_IS_ENABLED.equals(action)) { boolean b = m_bluetoothAdapter.isEnabled(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b)); return true; } else if (ACTION_GETADDRESS.equals(action)) { String address = m_bluetoothAdapter.getAddress(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, address)); return true; } else if (ACTION_GETNAME.equals(action)) { String name = m_bluetoothAdapter.getName(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, name)); return true; } else if (ACTION_REQUEST_DISCOVERABLE.equals(action)) { final int duration = args.getInt(0); this.callback_discoverable = callbackContext; Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, duration); this.cordova.startActivityForResult(this, intent, this.REQUEST_CODE_DISCOVERABLE); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); return true; } else if (ACTION_STARTDISCOVERY.equals(action)) { this.callback_discovery = callbackContext; m_discoveredDevices = new JSONArray(); // be sure there are no ongoing discovery m_bluetoothAdapter.cancelDiscovery(); if (!m_bluetoothAdapter.startDiscovery()) { String msg = "Unable to start discovery"; logErr(msg); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, msg)); } else { PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); } return true; } else if (ACTION_CANCELDISCOVERY.equals(action)) { if (m_bluetoothAdapter.cancelDiscovery()) callbackContext.success(); else callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR)); return true; } else if (ACTION_GETBONDEDDEVICES.equals(action)) { JSONArray bondedDevices = new JSONArray(); Set<BluetoothDevice> bondSet = m_bluetoothAdapter.getBondedDevices(); for (Iterator<BluetoothDevice> it = bondSet.iterator(); it.hasNext();) { BluetoothDevice bluetoothDevice = (BluetoothDevice) it.next(); JSONObject deviceInfo = new JSONObject(); deviceInfo.put("name", bluetoothDevice.getName()); deviceInfo.put("address", bluetoothDevice.getAddress()); deviceInfo.put("isBonded", true); bondedDevices.put(deviceInfo); } callbackContext.success(bondedDevices); return true; } else if (ACTION_FETCHUUIDS.equals(action)) { final String address = args.getString(0); this.callback_uuids = callbackContext; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { String msg = "Not supported, minimum SDK version is :" + Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1; logErr(msg); callbackContext.error(msg); return true; } try { logDbg("Listing UUIDs for : " + address); // Fetch UUIDs from bluetooth device BluetoothDevice bluetoothDevice = m_bluetoothAdapter.getRemoteDevice(address); // min api 15 !!! Method m = bluetoothDevice.getClass().getMethod("fetchUuidsWithSdp", (Class[]) null); m.invoke(bluetoothDevice, (Object[]) null); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); } catch (Exception e) { logErr(e.toString() + " / " + e.getMessage()); callbackContext.error(e.getMessage()); } return true; } else if (ACTION_CONNECT.equals(action)) { final String address = args.getString(0); final String uuid = args.getString(1); final boolean secure = args.getBoolean(2); this.callback_connect = callbackContext; cordova.getThreadPool().execute(new Runnable() { public void run() { BluetoothSocket socket = null; try { logDbg("Connecting..."); // Cancel discovery because it will slow down the connection if (m_bluetoothAdapter.isDiscovering()) m_bluetoothAdapter.cancelDiscovery(); //JWC adding /* BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address); //"74:45:8A:B2:4E:9A"); //Method m = device.getClass().getMethod("createInsecureRfcommSocket", // new Class[] { int.class }); //socket = (BluetoothSocket)m.invoke(device, Integer.valueOf(1)); socket = device.createRfcommSocketToServiceRecord(java.util.UUID.fromString(uuid)); */ ////// System.out.println("BluetoothPlugin2.ACTION_CONNECT address=" + address + ", uuid=" + uuid + ", secure=" + secure); BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address); //"74:45:8A:B2:4E:9A"); socket = device.createInsecureRfcommSocketToServiceRecord(java.util.UUID.fromString(uuid)); // for others devices its works with: // Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}); // for galaxy tab 2 with: //Method m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class}); //socket = (BluetoothSocket) m.invoke(device, 1); socket.connect(); /////JWC READ System.out.println("BluetoothPlugin2 trying to read right away..."); final int socketId = 0; //args.getInt(0); final int bufferSize = 512; //args.getInt(1); //this.callback_read = callbackContext; ReadThread readThread = new ReadThread(m_sockets.get(socketId), socketId, bufferSize); readThread.start(); m_readThreads.add(readThread); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); /////////////// /* JWC removing BluetoothDevice bluetoothDevice = m_bluetoothAdapter.getRemoteDevice( address); if (secure) { socket = connectSecureHelper( bluetoothDevice, UUID.fromString(uuid)); } else { socket = connectInsecureHelper( bluetoothDevice, UUID.fromString(uuid)); } */ } catch (Exception e) { logErr(e.toString() + " / " + e.getMessage()); callback_connect.error(e.getMessage()); } if (socket != null) { logDbg("Connected"); m_sockets.add(socket); int socketId = m_sockets.indexOf(socket); callback_connect.sendPluginResult(new PluginResult(PluginResult.Status.OK, socketId)); } else { callback_connect.error(0); } } }); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); return true; } else if (ACTION_DISCONNECT.equals(action)) { final int socketId = args.getInt(0); try { BluetoothSocket socket = m_sockets.get(socketId); logDbg("Close socket"); socket.close(); logDbg("Delete socket from list"); m_sockets.remove(socketId); for (int i = 0; i < m_readThreads.size(); i++) { if (m_readThreads.get(i).socketId == socketId) { m_readThreads.remove(i); break; } } callbackContext.success(); } catch (Exception e) { logErr(e.toString() + " / " + e.getMessage()); callbackContext.error(e.getMessage()); } return true; } else if (ACTION_LISTEN.equals(action)) { final String name = args.getString(0); final String uuid = args.getString(1); final boolean secure = args.getBoolean(2); System.out.println( "BluetoothPlugin2.ACTION_LISTEN name=" + name + ", uuid=" + uuid + ", secure=" + secure); this.callback_listen = callbackContext; if (m_listenThread != null) { m_listenThread.cancel(); m_listenThread = null; } m_listenThread = new ListenThread(this.cordova, name, UUID.fromString(uuid), secure); m_listenThread.start(); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); return true; } else if (ACTION_CANCEL_LISTENING.equals(action)) { if (m_listenThread != null) { m_listenThread.cancel(); } m_listenThread = null; callbackContext.success(); return true; } else if (ACTION_READ.equals(action)) { final int socketId = args.getInt(0); final int bufferSize = args.getInt(1); System.out.println("BluetoothPlugin2.ACTION_READ socketId=" + socketId + ", bufferSize=" + bufferSize); this.callback_read = callbackContext; ReadThread readThread = new ReadThread(m_sockets.get(socketId), socketId, bufferSize); readThread.start(); m_readThreads.add(readThread); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); return true; } else if (ACTION_WRITE.equals(action)) { final int socketId = args.getInt(0); final JSONArray jsonArray = args.getJSONArray(1); try { OutputStream outputStream = m_sockets.get(socketId).getOutputStream(); byte[] buffer = new byte[jsonArray.length()]; for (int i = 0; i < jsonArray.length(); i++) { buffer[i] = (byte) jsonArray.getInt(i); } outputStream.write(buffer); callbackContext.success(); } catch (Exception e) { logErr(e.toString() + " / " + e.getMessage()); callbackContext.error(e.getMessage()); } return true; } return false; }
From source file:com.github.akinaru.roboticbuttonpusher.bluetooth.BluetoothCustomManager.java
/** * Connect to device's GATT server/*from ww w.j a v a2 s .c om*/ */ @SuppressLint("NewApi") public boolean connect(String address) { if (mBluetoothAdapter == null || address == null) { Log.w(TAG, "BluetoothAdapter not initialized or unspecified address."); return false; } BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); boolean alreadyInList = false; if (bluetoothConnectionList.containsKey(address)) { alreadyInList = true; } if (alreadyInList) { Log.v(TAG, "reusing same connection"); BluetoothDeviceConn conn = (BluetoothDeviceConn) bluetoothConnectionList.get(address); conn.setGatt(device.connectGatt(context, false, conn.getGattCallback())); } else { BluetoothDeviceConn conn = new BluetoothDeviceConn(address, device.getName(), this); bluetoothConnectionList.put(address, conn); Log.v(TAG, "new connection"); //connect to gatt server on the device conn.setGatt(device.connectGatt(context, false, conn.getGattCallback())); } return true; }
From source file:com.improvelectronics.sync.android.SyncStreamingService.java
private void updatePairedDevices() { Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); if (pairedDevices == null || pairedDevices.size() == 0) return;//from www.j a v a 2 s .c o m if (DEBUG) Log.d(TAG, "searching for paired Syncs"); mPairedDevices.clear(); for (BluetoothDevice device : pairedDevices) { if (device.getName() != null && device.getName().equals("Sync")) { if (DEBUG) Log.d(TAG, "found a Boogie Board Sync"); mPairedDevices.add(device); } } // Connect to the first device that was found in the list of paired devices. if (mPairedDevices.size() > 0 && mState != STATE_CONNECTED) { BluetoothDevice device = mPairedDevices.get(0); // Device must first be checked to see if it has the most up to date firmware. // This check is done by ensuring the device has all the correct UUIDs. // If it doesn't have the CONNECT_UUID then the firmware is not the latest. boolean foundUuid = false; for (ParcelUuid uuid : device.getUuids()) { if (uuid.getUuid().equals(CONNECT_UUID)) foundUuid = true; } if (!foundUuid) { showUpdateFirmwareNotification(); } } }
From source file:com.evothings.BLE.java
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { if (mScanCallbackContext == null) { return;//w w w . jav a 2s . c o m } try { //System.out.println("onLeScan "+device.getAddress()+" "+rssi+" "+device.getName()); JSONObject o = new JSONObject(); o.put("address", device.getAddress()); o.put("rssi", rssi); o.put("name", device.getName()); o.put("scanRecord", Base64.encodeToString(scanRecord, Base64.NO_WRAP)); keepCallback(mScanCallbackContext, o); } catch (JSONException e) { mScanCallbackContext.error(e.toString()); } }
From source file:com.github.akinaru.bleanalyzer.bluetooth.BluetoothCustomManager.java
private void dispatchBtDevices(BluetoothDevice device, int rssi, final byte[] scanRecord) { if (scanningList.containsKey(device.getAddress())) { if (adListener != null && measurement.getBtDevice() != null && measurement.getBtDevice().getDeviceAddress().equals(device.getAddress())) { long ts = new Date().getTime(); measurement.getHistoryList().add(ts); adListener.onADframeReceived(ts, measurement.getHistoryList()); }/*ww w . j a va 2 s.c o m*/ } else { Log.i(TAG, "found a new Bluetooth device : " + device.getName() + " : " + device.getAddress()); scanningList.put(device.getAddress(), device); try { JSONObject object = new JSONObject(); object.put(JsonConstants.BT_ADDRESS, device.getAddress()); object.put(JsonConstants.BT_DEVICE_NAME, device.getName()); object.put(JsonConstants.BT_ADVERTISING_INTERVAL, -1); ArrayList<String> deviceInfo = new ArrayList<>(); deviceInfo.add(object.toString()); broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_DISCOVERED, deviceInfo); } catch (JSONException e) { e.printStackTrace(); } } }