List of usage examples for android.bluetooth BluetoothDevice createInsecureRfcommSocketToServiceRecord
@RequiresPermission(Manifest.permission.BLUETOOTH) public BluetoothSocket createInsecureRfcommSocketToServiceRecord(UUID uuid) throws IOException
From source file:Main.java
static synchronized BluetoothSocket getRfcommSocket(BluetoothDevice device, int numberOfRetries) { BluetoothSocket socket = null;/*w w w . j av a2 s . co m*/ numberOfRetries = numberOfRetries % 3; switch (numberOfRetries) { case 0: try { if (Build.VERSION.SDK_INT < 10) { socket = getInsecureRfcommSocketByReflection(device); } else { socket = device.createInsecureRfcommSocketToServiceRecord(BLUETOOTH_SPP_PROFILE); } break; } catch (Exception e) { } case 1: try { socket = device.createRfcommSocketToServiceRecord(BLUETOOTH_SPP_PROFILE); break; } catch (Exception e) { } case 2: try { socket = getRfcommSocketByReflection(device); } catch (Exception e) { } break; } return socket; }
From source file:org.mobisocial.corral.CorralClient.java
private Uri getFileOverBluetooth(DbUser user, SignedObj obj) throws IOException { String macStr = DbContactAttributes.getAttribute(mContext, user.getLocalId(), Contact.ATTR_BT_MAC); if (macStr == null) { throw new IOException("No bluetooth mac address for user"); }/*from ww w . j a v a 2 s .c o m*/ String uuidStr = DbContactAttributes.getAttribute(mContext, user.getLocalId(), Contact.ATTR_BT_CORRAL_UUID); if (uuidStr == null) { throw new IOException("No corral uuid for user"); } UUID uuid = UUID.fromString(uuidStr); BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); BluetoothDevice device = adapter.getRemoteDevice(macStr); BluetoothSocket socket; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) { socket = device.createInsecureRfcommSocketToServiceRecord(uuid); } else { socket = device.createRfcommSocketToServiceRecord(uuid); } // TODO: // Custom wire protocol, look for header bits to map to protocol handler. Log.d(TAG, "BJD BLUETOOTH CORRAL NOT READY: can't pull file over bluetooth."); return null; }
From source file:org.mobisocial.corral.CorralDownloadClient.java
private Uri getFileOverBluetooth(DbIdentity user, SignedObj obj, CorralDownloadFuture future, DownloadProgressCallback callback) throws IOException { callback.onProgress(DownloadState.PREPARING_CONNECTION, DownloadChannel.BLUETOOTH, 0); String macStr = DbContactAttributes.getAttribute(mContext, user.getLocalId(), DbContactAttributes.ATTR_BT_MAC); if (macStr == null) { throw new IOException("No bluetooth mac address for user"); }//from w w w. j av a 2 s. com String uuidStr = DbContactAttributes.getAttribute(mContext, user.getLocalId(), DbContactAttributes.ATTR_BT_CORRAL_UUID); if (uuidStr == null) { throw new IOException("No corral uuid for user"); } UUID uuid = UUID.fromString(uuidStr); BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); BluetoothDevice device = adapter.getRemoteDevice(macStr); BluetoothSocket socket; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) { socket = device.createInsecureRfcommSocketToServiceRecord(uuid); } else { socket = device.createRfcommSocketToServiceRecord(uuid); } // TODO: // Custom wire protocol, look for header bits to map to protocol handler. Log.d(TAG, "BJD BLUETOOTH CORRAL NOT READY: can't pull file over bluetooth."); return null; }
From source file:org.apache.cordova.plugin.BluetoothPlugin.java
/** * helper function//from ww w. ja va 2 s . c om * @param device * @param uuid * @return * @throws IOException */ @TargetApi(10) private BluetoothSocket connectInsecureHelper(BluetoothDevice device, UUID uuid) throws IOException { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD_MR1) { String msg = "Not supported, minimum SDK version is :" + Build.VERSION_CODES.GINGERBREAD_MR1; logErr(msg); return null; } BluetoothSocket bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid); bluetoothSocket.connect(); return bluetoothSocket; }
From source file:com.example.mego.adas.main.MainActivity.java
/** * Helper method to bluetooth connect with the device *//* w w w . jav a2s .c o m*/ private void connectBluetooth() { //show a progress dialog in the BluetoothServerActivity progressDialog = ProgressDialog.show(MainActivity.this, getString(R.string.bluetooth_connecting), getString(R.string.bluetooth_please_wait)); Completable.fromAction(() -> { if (btSocket == null || !isBtConnected) { //get the mobile bluetooth device myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //connects to the device's address and checks if it's available BluetoothDevice bluetoothDevice = myBluetoothAdapter.getRemoteDevice(address); //create a RFCOMM (SPP) connection btSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(myUUID); BluetoothAdapter.getDefaultAdapter().cancelDiscovery(); //start connection btSocket.connect(); } }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) .subscribe(new CompletableObserver() { @Override public void onSubscribe(Disposable d) { } @Override public void onComplete() { showToast(getString(R.string.bluetooth_connected)); connected = true; isBtConnected = true; progressDialog.dismiss(); mConnectedThread = new ConnectedThread(btSocket); mConnectedThread.start(); mConnectedThread.write("o"); } @Override public void onError(Throwable e) { progressDialog.dismiss(); showToast(getString(R.string.bluetooth_connection_failed)); finish(); } }); }
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 w w w . j a va2 s .c o m 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:org.metawatch.manager.MetaWatchService.java
@TargetApi(10) private boolean connect() { try {//from w w w .j a va 2 s. c om if (!Preferences.loaded) loadPreferences(this); MetaWatchService.fakeWatch = false; if (Preferences.watchMacAddress.equals("DIGITAL")) { MetaWatchService.fakeWatch = true; MetaWatchService.watchType = WatchType.DIGITAL; } if (Preferences.watchMacAddress.equals("ANALOG")) { MetaWatchService.fakeWatch = true; MetaWatchService.watchType = WatchType.ANALOG; } if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "Remote device address: '" + Preferences.watchMacAddress + "'"); if (!MetaWatchService.fakeWatch) { if (bluetoothAdapter == null) bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(Preferences.watchMacAddress); int currentapiVersion = android.os.Build.VERSION.SDK_INT; if (Preferences.skipSDP) { Method method; if (Preferences.insecureBtSocket && currentapiVersion >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) { method = bluetoothDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class }); } else { method = bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[] { int.class }); } bluetoothSocket = (BluetoothSocket) method.invoke(bluetoothDevice, 1); } else { UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); if (Preferences.insecureBtSocket && currentapiVersion >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) { bluetoothSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid); } else { bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid); } } bluetoothAdapter.cancelDiscovery(); bluetoothSocket.connect(); inputStream = bluetoothSocket.getInputStream(); outputStream = bluetoothSocket.getOutputStream(); } connectionState = ConnectionState.CONNECTED; setPreviousConnectionState(this, true); updateNotification(); Protocol.getInstance(MetaWatchService.this).getDeviceType(); NavigationManagement.processWatchConnection(this); // Unblock the message protocol queue, and the notification queue. mPauseQueue.open(); return true; } catch (IOException ioexception) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, ioexception.toString()); } catch (SecurityException e) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, e.toString()); } catch (NoSuchMethodException e) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, e.toString()); } catch (IllegalArgumentException e) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, e.toString()); } catch (IllegalAccessException e) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, e.toString()); } catch (InvocationTargetException e) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, e.toString()); } catch (NullPointerException e) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, e.toString()); } finally { } return false; }