List of usage examples for android.bluetooth BluetoothDevice getName
@RequiresPermission(Manifest.permission.BLUETOOTH)
public String getName()
From source file:no.nordicsemi.android.BLE.profile.BleProfileServiceReadyActivity.java
@Override public void onDeviceSelected(final BluetoothDevice device) { mLogSession = Logger.newSession(getApplicationContext(), getString(R.string.proximity_feature_title), device.getAddress(), device.getName()); mDeviceNameView.setText(mDeviceName = device.getName()); 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.v(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);//from w w w.jav a 2 s .c o m bindService(service, mServiceConnection, 0); }
From source file:org.deviceconnect.android.deviceplugin.health.fragment.HealthCareDeviceSettingsFragment.java
/** * Create a DeviceContainer from BluetoothDevice. * @param device Instance of BluetoothDevice * @return Instance of DeviceContainer/*from www . ja v a2s.c om*/ */ private DeviceContainer createContainer(final BluetoothDevice device) { DeviceContainer container = new DeviceContainer(); container.setName(device.getName()); container.setAddress(device.getAddress()); return container; }
From source file:com.phonegap.plugin.BluetoothPlugin.java
@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { Log.d(LOG_TAG, "Plugin Called"); this.callbackContext = callbackContext; PluginResult result = null;/*www . j a va 2 s. co m*/ //Looper.prepare(); btadapter = BluetoothAdapter.getDefaultAdapter(); found_devices = new ArrayList<BluetoothDevice>(); if (ACTION_DISCOVER_DEVICES.equals(action)) { try { Log.d(LOG_TAG, "We're in " + ACTION_DISCOVER_DEVICES); found_devices.clear(); discovering = true; if (btadapter.isDiscovering()) { btadapter.cancelDiscovery(); } Log.i(LOG_TAG, "Discovering devices..."); btadapter.startDiscovery(); result = new PluginResult(PluginResult.Status.NO_RESULT); result.setKeepCallback(true); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_DISCOVER_DEVICES, "Got Exception " + Ex.getMessage()); result = new PluginResult(PluginResult.Status.ERROR); } } else if (ACTION_IS_BT_ENABLED.equals(action)) { try { Log.d(LOG_TAG, "We're in " + ACTION_IS_BT_ENABLED); boolean isEnabled = btadapter.isEnabled(); Log.d("BluetoothPlugin - " + ACTION_IS_BT_ENABLED, "Returning " + "is Bluetooth Enabled? " + isEnabled); result = new PluginResult(PluginResult.Status.OK, isEnabled); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_IS_BT_ENABLED, "Got Exception " + Ex.getMessage()); result = new PluginResult(PluginResult.Status.ERROR); } } else if (ACTION_ENABLE_BT.equals(action)) { try { Log.d(LOG_TAG, "We're in " + ACTION_ENABLE_BT); boolean enabled = false; Log.d(LOG_TAG, "Enabling Bluetooth..."); if (btadapter.isEnabled()) { enabled = true; } else { enabled = btadapter.enable(); } Log.d("BluetoothPlugin - " + ACTION_ENABLE_BT, "Returning " + "Result: " + enabled); result = new PluginResult(PluginResult.Status.OK, enabled); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_ENABLE_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(PluginResult.Status.ERROR); } } else if (ACTION_DISABLE_BT.equals(action)) { try { Log.d(LOG_TAG, "We're in " + ACTION_DISABLE_BT); boolean disabled = false; Log.d(LOG_TAG, "Disabling Bluetooth..."); if (btadapter.isEnabled()) { disabled = btadapter.disable(); } else { disabled = true; } Log.d("BluetoothPlugin - " + ACTION_DISABLE_BT, "Returning " + "Result: " + disabled); result = new PluginResult(PluginResult.Status.OK, disabled); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_DISABLE_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(PluginResult.Status.ERROR); } } else if (ACTION_PAIR_BT.equals(action)) { try { Log.d(LOG_TAG, "We're in " + ACTION_PAIR_BT); String addressDevice = args.getString(0); if (btadapter.isDiscovering()) { btadapter.cancelDiscovery(); } BluetoothDevice device = btadapter.getRemoteDevice(addressDevice); boolean paired = false; Log.d(LOG_TAG, "Pairing with Bluetooth device with name " + device.getName() + " and address " + device.getAddress()); try { Method m = device.getClass().getMethod("createBond"); paired = (Boolean) m.invoke(device); } catch (Exception e) { e.printStackTrace(); } Log.d("BluetoothPlugin - " + ACTION_PAIR_BT, "Returning " + "Result: " + paired); result = new PluginResult(PluginResult.Status.OK, paired); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_PAIR_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(PluginResult.Status.ERROR); } } else if (ACTION_UNPAIR_BT.equals(action)) { try { Log.d(LOG_TAG, "We're in " + ACTION_UNPAIR_BT); String addressDevice = args.getString(0); if (btadapter.isDiscovering()) { btadapter.cancelDiscovery(); } BluetoothDevice device = btadapter.getRemoteDevice(addressDevice); boolean unpaired = false; Log.d(LOG_TAG, "Unpairing Bluetooth device with " + device.getName() + " and address " + device.getAddress()); try { Method m = device.getClass().getMethod("removeBond"); unpaired = (Boolean) m.invoke(device); } catch (Exception e) { e.printStackTrace(); } Log.d("BluetoothPlugin - " + ACTION_UNPAIR_BT, "Returning " + "Result: " + unpaired); result = new PluginResult(PluginResult.Status.OK, unpaired); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_UNPAIR_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(PluginResult.Status.ERROR); } } else if (ACTION_LIST_BOUND_DEVICES.equals(action)) { try { Log.d(LOG_TAG, "We're in " + ACTION_LIST_BOUND_DEVICES); Log.d(LOG_TAG, "Getting paired devices..."); Set<BluetoothDevice> pairedDevices = btadapter.getBondedDevices(); int count = 0; String resultBoundDevices = "[ "; if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { Log.i(LOG_TAG, device.getName() + " " + device.getAddress() + " " + device.getBondState()); if ((device.getName() != null) && (device.getBluetoothClass() != null)) { resultBoundDevices = resultBoundDevices + " { \"name\" : \"" + device.getName() + "\" ," + "\"address\" : \"" + device.getAddress() + "\" ," + "\"class\" : \"" + device.getBluetoothClass().getDeviceClass() + "\" }"; if (count < pairedDevices.size() - 1) resultBoundDevices = resultBoundDevices + ","; } else Log.i(LOG_TAG, device.getName() + " Problems retrieving attributes. Device not added "); count++; } } resultBoundDevices = resultBoundDevices + "] "; Log.d("BluetoothPlugin - " + ACTION_LIST_BOUND_DEVICES, "Returning " + resultBoundDevices); result = new PluginResult(PluginResult.Status.OK, resultBoundDevices); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_LIST_BOUND_DEVICES, "Got Exception " + Ex.getMessage()); result = new PluginResult(PluginResult.Status.ERROR); } } else if (ACTION_STOP_DISCOVERING_BT.equals(action)) { try { Log.d(LOG_TAG, "We're in " + ACTION_STOP_DISCOVERING_BT); boolean stopped = true; Log.d(LOG_TAG, "Stop Discovering Bluetooth Devices..."); if (btadapter.isDiscovering()) { Log.i(LOG_TAG, "Stop discovery..."); stopped = btadapter.cancelDiscovery(); discovering = false; } Log.d("BluetoothPlugin - " + ACTION_STOP_DISCOVERING_BT, "Returning " + "Result: " + stopped); result = new PluginResult(PluginResult.Status.OK, stopped); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_STOP_DISCOVERING_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(PluginResult.Status.ERROR); } } else if (ACTION_IS_BOUND_BT.equals(action)) { try { Log.d(LOG_TAG, "We're in " + ACTION_IS_BOUND_BT); String addressDevice = args.getString(0); BluetoothDevice device = btadapter.getRemoteDevice(addressDevice); Log.i(LOG_TAG, "BT Device in state " + device.getBondState()); boolean state = false; if (device != null && device.getBondState() == 12) state = true; else state = false; Log.d(LOG_TAG, "Is Bound with " + device.getName() + " - address " + device.getAddress()); Log.d("BluetoothPlugin - " + ACTION_IS_BOUND_BT, "Returning " + "Result: " + state); result = new PluginResult(PluginResult.Status.OK, state); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_IS_BOUND_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(PluginResult.Status.ERROR); } /* } else if ( ACTION_READ.equals(action) ) { final int socketId = args.getInt(0); final int bufferSize = 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); return true; */ } else { result = new PluginResult(PluginResult.Status.INVALID_ACTION); Log.d(LOG_TAG, "Invalid action : " + action + " passed"); } this.callbackContext.sendPluginResult(result); return true; }
From source file:it.angrydroids.epub3reader.MainActivity.java
private void ConnectBLEDevice() { for (BluetoothDevice listDev : deviceList) { if (listDev.getName().equals(UartService.BLEDeviceName)) { mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(listDev.getAddress()); mService.connect(listDev.getAddress()); break; }//w w w. java2 s . c o m } }
From source file:com.android.tv.settings.accessories.AddAccessoryActivity.java
protected void updateView() { if (mActionView == null || mStartTime == 0) { // view not yet ready, update will happen on first layout event return;/*from w ww. j a v a2s .c o m*/ } synchronized (mLock) { int prevNumDevices = mActions.size(); mActions.clear(); if (mActionFragment != null && mBtPairer != null) { // Add entries for the discovered Bluetooth devices for (BluetoothDevice bt : mBtDevices) { String title = bt.getName(); String desc; if (mCurrentTargetAddress.equalsIgnoreCase(bt.getAddress()) && !mCurrentTargetStatus.isEmpty()) { desc = mCurrentTargetStatus; } else if (mCancelledAddress.equalsIgnoreCase(bt.getAddress())) { desc = getString(R.string.accessory_state_canceled); } else { desc = bt.getAddress(); } mActions.add( new Action.Builder().key(KEY_BT_DEVICE).title(title).description(desc.toUpperCase()) .drawableResource(AccessoryUtils.getImageIdForDevice(bt)).build()); } } // Update the main fragment. ActionAdapter adapter = (ActionAdapter) mActionFragment.getAdapter(); if (adapter != null) { adapter.setActions(mActions); } if (!mActionsVisible && mActions.size() > 0) { mActionsVisible = true; long delay = ANIMATE_IN_DELAY - (SystemClock.elapsedRealtime() - mStartTime); if (delay > 0) { // Make sure we have a little bit of time after the activity // fades in // before we animate the actions in mActionView.postDelayed(new Runnable() { @Override public void run() { animateActionsIn(); } }, delay); } else { animateActionsIn(); } } if (mNoInputMode) { if (DEBUG) Log.d(TAG, "stopping auto-exit timer"); mAutoExitHandler.removeCallbacks(mAutoExitRunnable); if (mActions.size() == 1 && prevNumDevices == 0) { // first device added, start counter for autopair mMsgHandler.sendEmptyMessageDelayed(MSG_START_AUTOPAIR_COUNTDOWN, TIME_TO_START_AUTOPAIR_COUNT); } else { // Start timer count down for exiting activity. if (DEBUG) Log.d(TAG, "starting auto-exit timer"); mAutoExitHandler.postDelayed(mAutoExitRunnable, EXIT_TIMEOUT_MILLIS); if (mActions.size() > 1) { // More than one device found, cancel auto pair cancelPairingCountdown(); if (!mShowingMultiFragment && !mFragmentTransactionPending) { if (mActionsAnimationDone) { switchToMultipleDevicesFragment(); } else { mFragmentTransactionPending = true; } } } } } } }
From source file:com.android.server.MigratorService.java
private void makeDeviceList() { /*get list of devices which can be migrated*/ if (supported) { /*get paired devices*/ Set<BluetoothDevice> pairedDevices = mAdapter.getBondedDevices(); devicelist = new ArrayList<String>(); if (pairedDevices.size() > 0) { /*if paired device is exist*/ for (BluetoothDevice device : pairedDevices) { /* choice phone or tablet*/ if (debug) Log.w(TAG, "device name:" + device.getName()); int code = device.getBluetoothClass().getMajorDeviceClass(); if (code == BluetoothClass.Device.Major.PHONE) { devicelist.add(device.getName() + "\n" + device.getAddress()); devices.add(device); } else if (code == BluetoothClass.Device.Major.COMPUTER) { devicelist.add(device.getName() + "\n" + device.getAddress()); devices.add(device); }// w w w . j a v a2 s . c om } } } }
From source file:org.bcsphere.bluetooth.BluetoothG43plus.java
private void startScanManage(BluetoothDevice device, int rssi, byte[] scanRecord) { JSONObject obj = new JSONObject(); Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress()); Tools.addProperty(obj, Tools.DEVICE_NAME, device.getName()); Tools.addProperty(obj, Tools.IS_CONNECTED, Tools.IS_FALSE); Tools.addProperty(obj, Tools.RSSI, rssi); Tools.addProperty(obj, Tools.ADVERTISEMENT_DATA, Tools.decodeAdvData(scanRecord)); Tools.addProperty(obj, Tools.TYPE, "BLE"); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, obj); pluginResult.setKeepCallback(true);//from w w w . j a v a 2s . co m addEventListenerCC.get(Tools.NEW_ADV_PACKET).sendPluginResult(pluginResult); }
From source file:com.piusvelte.taplock.client.core.TapLockSettings.java
private void addDevice() { // Get a set of currently paired devices BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); if (btAdapter.isEnabled()) { Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices(); // launch dialog to select device if (pairedDevices.size() > 0) { int p = 0; final String[] pairedDeviceNames = new String[pairedDevices.size()]; final String[] pairedDeviceAddresses = new String[pairedDevices.size()]; for (BluetoothDevice device : pairedDevices) { pairedDeviceNames[p] = device.getName(); pairedDeviceAddresses[p++] = device.getAddress(); }//from w ww .j a v a 2 s . co m mDialog = new AlertDialog.Builder(TapLockSettings.this) .setItems(pairedDeviceNames, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { addNewDevice(pairedDeviceNames[which], pairedDeviceAddresses[which]); } }) .setPositiveButton(getString(R.string.btn_bt_scan), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mServiceInterface != null) { try { mServiceInterface.requestDiscovery(); mProgressDialog = new ProgressDialog(TapLockSettings.this); mProgressDialog.setMessage(getString(R.string.msg_scanning)); mProgressDialog.setCancelable(true); mProgressDialog.show(); } catch (RemoteException e) { Log.e(TAG, e.toString()); } } } }).create(); mDialog.show(); } else { if (mServiceInterface != null) { try { mServiceInterface.requestDiscovery(); mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage(getString(R.string.msg_scanning)); mProgressDialog.setCancelable(true); mProgressDialog.show(); } catch (RemoteException e) { Log.e(TAG, e.toString()); } } } } else { mDialog = new AlertDialog.Builder(TapLockSettings.this).setTitle(R.string.ttl_enablebt) .setMessage(R.string.msg_enablebt) .setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mServiceInterface != null) { try { mServiceInterface.enableBluetooth(); } catch (RemoteException e) { Log.e(TAG, e.toString()); } } } }).create(); mDialog.show(); } }
From source file:org.apache.cordova.plugin.BluetoothPlugin.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 ava 2 s. co 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(); 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); 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); 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.lsc.hellocordova.BluetoothPlugin.java
@Override public PluginResult execute(String action, JSONArray arg1, String callbackId) { Log.d("BluetoothPlugin", "Plugin Called"); PluginResult result = null;/*from ww w .jav a 2s . c o m*/ context = (Context) this.ctx; // Register for broadcasts when a device is discovered IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); context.registerReceiver(mReceiver, filter); // Register for broadcasts when discovery starts filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED); context.registerReceiver(mReceiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); context.registerReceiver(mReceiver, filter); // Register for broadcasts when connectivity state changes filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); context.registerReceiver(mReceiver, filter); Looper.prepare(); btadapter = BluetoothAdapter.getDefaultAdapter(); found_devices = new ArrayList<BluetoothDevice>(); if (ACTION_DISCOVER_DEVICES.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_DISCOVER_DEVICES); found_devices.clear(); discovering = true; if (btadapter.isDiscovering()) { btadapter.cancelDiscovery(); } Log.i("BluetoothPlugin", "Discovering devices..."); btadapter.startDiscovery(); while (discovering) { } String devicesFound = null; int count = 0; devicesFound = "["; for (BluetoothDevice device : found_devices) { Log.i("BluetoothPlugin", device.getName() + " " + device.getAddress() + " " + device.getBondState()); if ((device.getName() != null) && (device.getBluetoothClass() != null)) { devicesFound = devicesFound + " { \"name\" : \"" + device.getName() + "\" ," + "\"address\" : \"" + device.getAddress() + "\" ," + "\"class\" : \"" + device.getBluetoothClass().getDeviceClass() + "\" }"; if (count < found_devices.size() - 1) devicesFound = devicesFound + ","; } else Log.i("BluetoothPlugin", device.getName() + " Problems retrieving attributes. Device not added "); count++; } devicesFound = devicesFound + "] "; Log.d("BluetoothPlugin - " + ACTION_DISCOVER_DEVICES, "Returning: " + devicesFound); result = new PluginResult(Status.OK, devicesFound); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_DISCOVER_DEVICES, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_IS_BT_ENABLED.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_IS_BT_ENABLED); boolean isEnabled = btadapter.isEnabled(); Log.d("BluetoothPlugin - " + ACTION_IS_BT_ENABLED, "Returning " + "is Bluetooth Enabled? " + isEnabled); result = new PluginResult(Status.OK, isEnabled); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_IS_BT_ENABLED, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_ENABLE_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_ENABLE_BT); boolean enabled = false; Log.d("BluetoothPlugin", "Enabling Bluetooth..."); if (btadapter.isEnabled()) { enabled = true; } else { enabled = btadapter.enable(); } Log.d("BluetoothPlugin - " + ACTION_ENABLE_BT, "Returning " + "Result: " + enabled); result = new PluginResult(Status.OK, enabled); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_ENABLE_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_DISABLE_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_DISABLE_BT); boolean disabled = false; Log.d("BluetoothPlugin", "Disabling Bluetooth..."); if (btadapter.isEnabled()) { disabled = btadapter.disable(); } else { disabled = true; } Log.d("BluetoothPlugin - " + ACTION_DISABLE_BT, "Returning " + "Result: " + disabled); result = new PluginResult(Status.OK, disabled); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_DISABLE_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_PAIR_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_PAIR_BT); String addressDevice = arg1.getString(0); if (btadapter.isDiscovering()) { btadapter.cancelDiscovery(); } BluetoothDevice device = btadapter.getRemoteDevice(addressDevice); boolean paired = false; Log.d("BluetoothPlugin", "Pairing with Bluetooth device with name " + device.getName() + " and address " + device.getAddress()); try { Method m = device.getClass().getMethod("createBond"); paired = (Boolean) m.invoke(device); } catch (Exception e) { e.printStackTrace(); } Log.d("BluetoothPlugin - " + ACTION_PAIR_BT, "Returning " + "Result: " + paired); result = new PluginResult(Status.OK, paired); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_PAIR_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_UNPAIR_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_UNPAIR_BT); String addressDevice = arg1.getString(0); if (btadapter.isDiscovering()) { btadapter.cancelDiscovery(); } BluetoothDevice device = btadapter.getRemoteDevice(addressDevice); boolean unpaired = false; Log.d("BluetoothPlugin", "Unpairing Bluetooth device with " + device.getName() + " and address " + device.getAddress()); try { Method m = device.getClass().getMethod("removeBond"); unpaired = (Boolean) m.invoke(device); } catch (Exception e) { e.printStackTrace(); } Log.d("BluetoothPlugin - " + ACTION_UNPAIR_BT, "Returning " + "Result: " + unpaired); result = new PluginResult(Status.OK, unpaired); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_UNPAIR_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_LIST_BOUND_DEVICES.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_LIST_BOUND_DEVICES); Log.d("BluetoothPlugin", "Getting paired devices..."); Set<BluetoothDevice> pairedDevices = btadapter.getBondedDevices(); int count = 0; String resultBoundDevices = "[ "; if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { Log.i("BluetoothPlugin", device.getName() + " " + device.getAddress() + " " + device.getBondState()); if ((device.getName() != null) && (device.getBluetoothClass() != null)) { resultBoundDevices = resultBoundDevices + " { \"name\" : \"" + device.getName() + "\" ," + "\"address\" : \"" + device.getAddress() + "\" ," + "\"class\" : \"" + device.getBluetoothClass().getDeviceClass() + "\" }"; if (count < pairedDevices.size() - 1) resultBoundDevices = resultBoundDevices + ","; } else Log.i("BluetoothPlugin", device.getName() + " Problems retrieving attributes. Device not added "); count++; } } resultBoundDevices = resultBoundDevices + "] "; Log.d("BluetoothPlugin - " + ACTION_LIST_BOUND_DEVICES, "Returning " + resultBoundDevices); result = new PluginResult(Status.OK, resultBoundDevices); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_LIST_BOUND_DEVICES, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_STOP_DISCOVERING_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_STOP_DISCOVERING_BT); boolean stopped = true; Log.d("BluetoothPlugin", "Stop Discovering Bluetooth Devices..."); if (btadapter.isDiscovering()) { Log.i("BluetoothPlugin", "Stop discovery..."); stopped = btadapter.cancelDiscovery(); discovering = false; } Log.d("BluetoothPlugin - " + ACTION_STOP_DISCOVERING_BT, "Returning " + "Result: " + stopped); result = new PluginResult(Status.OK, stopped); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_STOP_DISCOVERING_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_IS_BOUND_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_IS_BOUND_BT); String addressDevice = arg1.getString(0); BluetoothDevice device = btadapter.getRemoteDevice(addressDevice); Log.i("BluetoothPlugin", "BT Device in state " + device.getBondState()); boolean state = false; if (device != null && device.getBondState() == 12) state = true; else state = false; Log.d("BluetoothPlugin", "Is Bound with " + device.getName() + " - address " + device.getAddress()); Log.d("BluetoothPlugin - " + ACTION_IS_BOUND_BT, "Returning " + "Result: " + state); result = new PluginResult(Status.OK, state); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_IS_BOUND_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_OPEN_SOCKET.equals(action)) { Log.d("BluetoothPlugin", "We're in " + ACTION_OPEN_SOCKET); try { String addressDevice = arg1.getString(0); openSocket(addressDevice); result = new PluginResult(Status.OK, "true"); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_OPEN_SOCKET, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_MESSAGE_SOCKET.equals(action)) { Log.d("BluetoothPlugin", "We're in " + ACTION_MESSAGE_SOCKET); try { String msg = arg1.getString(0); sendData(msg); result = new PluginResult(Status.OK, "true"); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_MESSAGE_SOCKET, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_CLOSE_SOCKET.equals(action)) { Log.d("BluetoothPlugin", "We're in " + ACTION_CLOSE_SOCKET); try { closeSocket(); result = new PluginResult(Status.OK, "true"); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_CLOSE_SOCKET, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_PING_SOCKET.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_PING_SOCKET); String data = "{"; data = data + "\"count\": " + Integer.toString(pingCount) + ","; String items = ""; for (String item : pingData) { items = items + ",\"" + item + "\""; } data = data + " \"data\" : [" + items.substring(1) + " ]"; data = data + "}"; result = new PluginResult(Status.OK, data); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_PING_SOCKET, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else { result = new PluginResult(Status.INVALID_ACTION); Log.d("BluetoothPlugin", "Invalid action : " + action + " passed"); } return result; }