List of usage examples for android.bluetooth BluetoothDevice getName
@RequiresPermission(Manifest.permission.BLUETOOTH)
public String getName()
From source file:com.landenlabs.all_devtool.NetFragment.java
public void updateList() { // Time today = new Time(Time.getCurrentTimezone()); // today.setToNow(); // today.format(" %H:%M:%S") Date dt = new Date(); m_titleTime.setText(m_timeFormat.format(dt)); boolean expandAll = m_list.isEmpty(); m_list.clear();//from ww w . java 2 s . co m // Swap colors int color = m_rowColor1; m_rowColor1 = m_rowColor2; m_rowColor2 = color; ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE); try { String androidIDStr = Settings.Secure.getString(getContext().getContentResolver(), Settings.Secure.ANDROID_ID); addBuild("Android ID", androidIDStr); try { AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getContext()); final String adIdStr = adInfo.getId(); final boolean isLAT = adInfo.isLimitAdTrackingEnabled(); addBuild("Ad ID", adIdStr); } catch (IOException e) { // Unrecoverable error connecting to Google Play services (e.g., // the old version of the service doesn't support getting AdvertisingId). } catch (GooglePlayServicesNotAvailableException e) { // Google Play services is not available entirely. } /* try { InstanceID instanceID = InstanceID.getInstance(getContext()); if (instanceID != null) { // Requires a Google Developer project ID. String authorizedEntity = "<need to make this on google developer site>"; instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); addBuild("Instance ID", instanceID.getId()); } } catch (Exception ex) { } */ ConfigurationInfo info = actMgr.getDeviceConfigurationInfo(); addBuild("OpenGL", info.getGlEsVersion()); } catch (Exception ex) { m_log.e(ex.getMessage()); } // --------------- Connection Services ------------- try { ConnectivityManager connMgr = (ConnectivityManager) getActivity() .getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo netInfo = connMgr.getActiveNetworkInfo(); if (netInfo != null) { Map<String, String> netListStr = new LinkedHashMap<String, String>(); putIf(netListStr, "Available", "Yes", netInfo.isAvailable()); putIf(netListStr, "Connected", "Yes", netInfo.isConnected()); putIf(netListStr, "Connecting", "Yes", !netInfo.isConnected() && netInfo.isConnectedOrConnecting()); putIf(netListStr, "Roaming", "Yes", netInfo.isRoaming()); putIf(netListStr, "Extra", netInfo.getExtraInfo(), !TextUtils.isEmpty(netInfo.getExtraInfo())); putIf(netListStr, "WhyFailed", netInfo.getReason(), !TextUtils.isEmpty(netInfo.getReason())); if (Build.VERSION.SDK_INT >= 16) { putIf(netListStr, "Metered", "Avoid heavy use", connMgr.isActiveNetworkMetered()); } netListStr.put("NetworkType", netInfo.getTypeName()); if (connMgr.getAllNetworkInfo().length > 1) { netListStr.put("Available Networks:", " "); for (NetworkInfo netI : connMgr.getAllNetworkInfo()) { if (netI.isAvailable()) { netListStr.put(" " + netI.getTypeName(), netI.isAvailable() ? "Yes" : "No"); } } } if (netInfo.isConnected()) { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { if (inetAddress.getHostAddress() != null) { String ipType = (inetAddress instanceof Inet4Address) ? "IPv4" : "IPv6"; netListStr.put(intf.getName() + " " + ipType, inetAddress.getHostAddress()); } // if (!TextUtils.isEmpty(inetAddress.getHostName())) // listStr.put( "HostName", inetAddress.getHostName()); } } } } catch (Exception ex) { m_log.e("Network %s", ex.getMessage()); } } addBuild("Network...", netListStr); } } catch (Exception ex) { m_log.e("Network %s", ex.getMessage()); } // --------------- Telephony Services ------------- TelephonyManager telephonyManager = (TelephonyManager) getActivity() .getSystemService(Context.TELEPHONY_SERVICE); if (telephonyManager != null) { Map<String, String> cellListStr = new LinkedHashMap<String, String>(); try { cellListStr.put("Version", telephonyManager.getDeviceSoftwareVersion()); cellListStr.put("Number", telephonyManager.getLine1Number()); cellListStr.put("Service", telephonyManager.getNetworkOperatorName()); cellListStr.put("Roaming", telephonyManager.isNetworkRoaming() ? "Yes" : "No"); cellListStr.put("Type", getNetworkTypeName(telephonyManager.getNetworkType())); if (Build.VERSION.SDK_INT >= 17) { if (telephonyManager.getAllCellInfo() != null) { for (CellInfo cellInfo : telephonyManager.getAllCellInfo()) { String cellName = cellInfo.getClass().getSimpleName(); int level = 0; if (cellInfo instanceof CellInfoCdma) { level = ((CellInfoCdma) cellInfo).getCellSignalStrength().getLevel(); } else if (cellInfo instanceof CellInfoGsm) { level = ((CellInfoGsm) cellInfo).getCellSignalStrength().getLevel(); } else if (cellInfo instanceof CellInfoLte) { level = ((CellInfoLte) cellInfo).getCellSignalStrength().getLevel(); } else if (cellInfo instanceof CellInfoWcdma) { if (Build.VERSION.SDK_INT >= 18) { level = ((CellInfoWcdma) cellInfo).getCellSignalStrength().getLevel(); } } cellListStr.put(cellName, "Level% " + String.valueOf(100 * level / 4)); } } } for (NeighboringCellInfo cellInfo : telephonyManager.getNeighboringCellInfo()) { int level = cellInfo.getRssi(); cellListStr.put("Cell level%", String.valueOf(100 * level / 31)); } } catch (Exception ex) { m_log.e("Cell %s", ex.getMessage()); } if (!cellListStr.isEmpty()) { addBuild("Cell...", cellListStr); } } // --------------- Bluetooth Services (API18) ------------- if (Build.VERSION.SDK_INT >= 18) { try { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter != null) { Map<String, String> btListStr = new LinkedHashMap<String, String>(); btListStr.put("Enabled", bluetoothAdapter.isEnabled() ? "yes" : "no"); btListStr.put("Name", bluetoothAdapter.getName()); btListStr.put("ScanMode", String.valueOf(bluetoothAdapter.getScanMode())); btListStr.put("State", String.valueOf(bluetoothAdapter.getState())); Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); // If there are paired devices if (pairedDevices.size() > 0) { // Loop through paired devices for (BluetoothDevice device : pairedDevices) { // Add the name and address to an array adapter to show in a ListView btListStr.put("Paired:" + device.getName(), device.getAddress()); } } BluetoothManager btMgr = (BluetoothManager) getActivity() .getSystemService(Context.BLUETOOTH_SERVICE); if (btMgr != null) { // btMgr.getAdapter(). } addBuild("Bluetooth", btListStr); } } catch (Exception ex) { } } // --------------- Wifi Services ------------- final WifiManager wifiMgr = (WifiManager) getContext().getApplicationContext() .getSystemService(Context.WIFI_SERVICE); if (wifiMgr != null && wifiMgr.isWifiEnabled() && wifiMgr.getDhcpInfo() != null) { if (mSystemBroadcastReceiver == null) { mSystemBroadcastReceiver = new SystemBroadcastReceiver(wifiMgr); getActivity().registerReceiver(mSystemBroadcastReceiver, INTENT_FILTER_SCAN_AVAILABLE); } if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if (wifiMgr.getScanResults() == null || wifiMgr.getScanResults().size() != mLastScanSize) { mLastScanSize = wifiMgr.getScanResults().size(); wifiMgr.startScan(); } } Map<String, String> wifiListStr = new LinkedHashMap<String, String>(); try { DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo(); wifiListStr.put("DNS1", Formatter.formatIpAddress(dhcpInfo.dns1)); wifiListStr.put("DNS2", Formatter.formatIpAddress(dhcpInfo.dns2)); wifiListStr.put("Default Gateway", Formatter.formatIpAddress(dhcpInfo.gateway)); wifiListStr.put("IP Address", Formatter.formatIpAddress(dhcpInfo.ipAddress)); wifiListStr.put("Subnet Mask", Formatter.formatIpAddress(dhcpInfo.netmask)); wifiListStr.put("Server IP", Formatter.formatIpAddress(dhcpInfo.serverAddress)); wifiListStr.put("Lease Time(sec)", String.valueOf(dhcpInfo.leaseDuration)); WifiInfo wifiInfo = wifiMgr.getConnectionInfo(); if (wifiInfo != null) { wifiListStr.put("LinkSpeed Mbps", String.valueOf(wifiInfo.getLinkSpeed())); int numberOfLevels = 10; int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels + 1); wifiListStr.put("Signal%", String.valueOf(100 * level / numberOfLevels)); if (Build.VERSION.SDK_INT >= 23) { wifiListStr.put("MAC", getMacAddr()); } else { wifiListStr.put("MAC", wifiInfo.getMacAddress()); } } } catch (Exception ex) { m_log.e("Wifi %s", ex.getMessage()); } if (!wifiListStr.isEmpty()) { addBuild("WiFi...", wifiListStr); } try { if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { List<ScanResult> listWifi = wifiMgr.getScanResults(); if (listWifi != null && !listWifi.isEmpty()) { int idx = 0; for (ScanResult scanResult : listWifi) { Map<String, String> wifiScanListStr = new LinkedHashMap<String, String>(); wifiScanListStr.put("SSID", scanResult.SSID); if (Build.VERSION.SDK_INT >= 23) { wifiScanListStr.put(" Name", scanResult.operatorFriendlyName.toString()); wifiScanListStr.put(" Venue", scanResult.venueName.toString()); } // wifiScanListStr.put(" BSSID ",scanResult.BSSID); wifiScanListStr.put(" Capabilities", scanResult.capabilities); // wifiScanListStr.put(" Center Freq", String.valueOf(scanResult.centerFreq0)); // wifiScanListStr.put(" Freq width", String.valueOf(scanResult.channelWidth)); wifiScanListStr.put(" Level, Freq", String.format("%d, %d", scanResult.level, scanResult.frequency)); if (Build.VERSION.SDK_INT >= 17) { Date wifiTime = new Date(scanResult.timestamp); wifiScanListStr.put(" Time", wifiTime.toLocaleString()); } addBuild(String.format("WiFiScan #%d", ++idx), wifiScanListStr); } } } } catch (Exception ex) { m_log.e("WifiList %s", ex.getMessage()); } try { List<WifiConfiguration> listWifiCfg = wifiMgr.getConfiguredNetworks(); for (WifiConfiguration wifiCfg : listWifiCfg) { Map<String, String> wifiCfgListStr = new LinkedHashMap<String, String>(); if (Build.VERSION.SDK_INT >= 23) { wifiCfgListStr.put("Name", wifiCfg.providerFriendlyName); } wifiCfgListStr.put("SSID", wifiCfg.SSID); String netStatus = ""; switch (wifiCfg.status) { case WifiConfiguration.Status.CURRENT: netStatus = "Connected"; break; case WifiConfiguration.Status.DISABLED: netStatus = "Disabled"; break; case WifiConfiguration.Status.ENABLED: netStatus = "Enabled"; break; } wifiCfgListStr.put(" Status", netStatus); wifiCfgListStr.put(" Priority", String.valueOf(wifiCfg.priority)); if (null != wifiCfg.wepKeys) { // wifiCfgListStr.put(" wepKeys", TextUtils.join(",", wifiCfg.wepKeys)); } String protocols = ""; if (wifiCfg.allowedProtocols.get(WifiConfiguration.Protocol.RSN)) protocols = "RSN "; if (wifiCfg.allowedProtocols.get(WifiConfiguration.Protocol.WPA)) protocols = protocols + "WPA "; wifiCfgListStr.put(" Protocols", protocols); String keyProt = ""; if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)) keyProt = "none"; if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP)) keyProt = "WPA+EAP "; if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) keyProt = "WPA+PSK "; wifiCfgListStr.put(" Keys", keyProt); if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)) { // Remove network connections with no Password. // wifiMgr.removeNetwork(wifiCfg.networkId); } addBuild("WiFiCfg #" + wifiCfg.networkId, wifiCfgListStr); } } catch (Exception ex) { m_log.e("Wifi Cfg List %s", ex.getMessage()); } } if (expandAll) { // updateList(); int count = m_list.size(); for (int position = 0; position < count; position++) m_listView.expandGroup(position); } m_adapter.notifyDataSetChanged(); }
From source file:org.bcsphere.bluetooth.BluetoothSamAPI.java
@Override public void getPairedDevices(JSONArray json, CallbackContext callbackContext) { Log.i(TAG, "getPairedDevices"); if (!isInitialized(callbackContext)) { return;/*from ww w .j a va 2 s . c o m*/ } Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices(); JSONArray jsonDevices = new JSONArray(); for (BluetoothDevice device : bondedDevices) { JSONObject jsonDevice = new JSONObject(); Tools.addProperty(jsonDevice, Tools.DEVICE_ID, device.getAddress()); Tools.addProperty(jsonDevice, Tools.DEVICE_NAME, device.getName()); jsonDevices.put(jsonDevice); } callbackContext.success(jsonDevices); }
From source file:com.notalenthack.blaster.BluetoothSerialService.java
/** * 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 *///from w w w . j av a 2s.co m public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) { if (D) Log.d(TAG, "connected"); // Cancel the thread that completed the connection if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } // Cancel any thread currently running a connection if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } // Start the thread to manage the connection and perform transmissions mConnectedThread = new ConnectedThread(socket); mConnectedThread.start(); // Send the name of the connected device back to the UI Activity Message msg = mHandler.obtainMessage(Constants.MESSAGE_DEVICE_NAME_CMD); Bundle bundle = new Bundle(); bundle.putString(Constants.KEY_DEVICE_NAME, device.getName()); msg.setData(bundle); mHandler.sendMessage(msg); setState(STATE_CONNECTED); }
From source file:org.bcsphere.bluetooth.BluetoothSamAPI.java
@Override public void getConnectedDevices(JSONArray json, CallbackContext callbackContext) { Log.i(TAG, "getConnectedDevices"); if (!isInitialized(callbackContext)) { return;// w w w . jav a 2 s.c o m } @SuppressWarnings("unchecked") List<BluetoothDevice> bluetoothDevices = bluetoothGatt.getConnectedDevices(); JSONArray jsonDevices = new JSONArray(); for (BluetoothDevice device : bluetoothDevices) { JSONObject jsonDevice = new JSONObject(); Tools.addProperty(jsonDevice, Tools.DEVICE_ID, device.getAddress()); Tools.addProperty(jsonDevice, Tools.DEVICE_NAME, device.getName()); jsonDevices.put(jsonDevice); } callbackContext.success(jsonDevices); }
From source file:com.bluetooth.mwoolley.microbitbledemo.ui.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setButtonText();/*from www . j av a 2s . c o m*/ getSupportActionBar().setTitle(R.string.screen_title_main); showMsg(Utility.htmlColorGreen("Ready")); Settings.getInstance().restore(this); ble_device_list_adapter = new ListAdapter(); ListView listView = (ListView) this.findViewById(R.id.deviceList); listView.setAdapter(ble_device_list_adapter); registerReceiver(broadcastReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)); ble_scanner = BleScannerFactory.getBleScanner(this.getApplicationContext()); ble_scanner.setDevice_name_start(DEVICE_NAME_START); ble_scanner.setSelect_bonded_devices_only(true); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (ble_scanning) { setScanState(false); ble_scanner.stopScanning(); } BluetoothDevice device = ble_device_list_adapter.getDevice(position); if (device.getBondState() == BluetoothDevice.BOND_NONE && Settings.getInstance().isFilter_unpaired_devices()) { device.createBond(); showMsg(Utility.htmlColorRed("Selected micro:bit must be paired - pairing now")); return; } try { MainActivity.this.unregisterReceiver(broadcastReceiver); } catch (Exception e) { // ignore! } if (toast != null) { toast.cancel(); } MicroBit microbit = MicroBit.getInstance(); microbit.setBluetooth_device(device); Intent intent = new Intent(MainActivity.this, MenuActivity.class); intent.putExtra(MenuActivity.EXTRA_NAME, device.getName()); intent.putExtra(MenuActivity.EXTRA_ID, device.getAddress()); startActivity(intent); } }); }
From source file:org.bcsphere.bluetooth.BluetoothSamAPI.java
@Override public void getScanData(JSONArray json, CallbackContext callbackContext) { Log.i(TAG, "getScanData"); JSONArray jsonDevices = new JSONArray(); for (BluetoothDevice device : bluetoothDevices) { String deviceID = device.getAddress(); JSONObject jsonDevice = new JSONObject(); Tools.addProperty(jsonDevice, Tools.DEVICE_ID, deviceID); Tools.addProperty(jsonDevice, Tools.DEVICE_NAME, device.getName()); Tools.addProperty(jsonDevice, Tools.IS_CONNECTED, bluetoothGatt.getConnectedDevices().contains(device)); Tools.addProperty(jsonDevice, Tools.RSSI, mapRssiData.get(deviceID)); Tools.addProperty(jsonDevice, Tools.ADVERTISEMENT_DATA, Tools.decodeAdvData(mapDeviceAdvData.get(deviceID))); jsonDevices.put(jsonDevice);/* ww w . jav a2 s .c o m*/ } callbackContext.success(jsonDevices); }
From source file:com.android.dragonkeyboardfirmwareupdater.KeyboardFirmwareUpdateService.java
/** * Handles intents ACTION_CONNECTION_STATE_CHANGED, ACTION_STATE_CHANGED, * ACTION_BOND_STATE_CHANGED, ACTION_KEYBOARD_UPDATE_CONFIRMED. * <p/>//from www . j a va 2 s.c o m * [ACTION_STATE_CHANGED] * This action is used to keep track of ON/OFF state change on the system Bluetooth adapter. * The * purpose is to synchronize the local Bluetooth connectivity with system Bluetooth state. * <p/> * [ACTION_CONNECTION_STATE_CHANGED] * This action is used to keep track of the connection change on the target device. The purpose * is to synchronize the connection cycles of the local GATT connection and the system * Bluetooth * connection. * <p/> * [ACTION_BOND_STATE_CHANGED] * This action is used to keep track of the bond state change on the target device. The purpose * is to the connection cycles of the local GATT connection and the system Bluetooth * connection. * <p/> * [ACTION_KEYBOARD_UPDATE_CONFIRMED] * This action is used to receive the update confirmation from the user. The purpose is to * trigger DFU process. */ private void onHandleIntent(Context context, Intent intent) { final String action = intent.getAction(); Log.d(TAG, "onHandleIntent: Received action: " + action); if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(action)) { if (!isBluetoothEnabled()) { Log.w(TAG, "onHandleIntent: Bluetooth connectivity not enabled"); return; } // Match the connected device with the default keyboard name. Bundle extras = intent.getExtras(); if (extras == null) return; final BluetoothDevice device = extras.getParcelable(BluetoothDevice.EXTRA_DEVICE); final int deviceConnectionState = extras.getInt(BluetoothAdapter.EXTRA_CONNECTION_STATE); Log.d(TAG, "onHandleIntent: " + device.getName() + " [" + device.getAddress() + "] change to state: " + deviceConnectionState); // Match the name of the target keyboard. if (!isTargetKeyboard(device)) return; if (deviceConnectionState == BluetoothAdapter.STATE_CONNECTED) { // Prevent the second keyboard from using the service. if (isUpdateServiceInUse()) return; obtainKeyboardInfo(device.getName(), device.getAddress()); if (mDfuStatus != DFU_STATE_INFO_READY) { Log.w(TAG, "onHandleIntent: DFU preparation failed"); changeDfuStatus(DFU_STATE_OBTAIN_INFO_ERROR); return; } showUpdateNotification(); } else if (deviceConnectionState == BluetoothAdapter.STATE_DISCONNECTING) { handleGattDisconnection(); } } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) { final int adapterState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); if (adapterState == BluetoothAdapter.STATE_ON) { if (!isBluetoothEnabled()) enableBluetoothConnectivity(); } else if (adapterState == BluetoothAdapter.STATE_TURNING_OFF) { // Terminate update process and disable Bluetooth connectivity. disableBluetoothConnectivity(); // Since BluetoothAdapter has been disabled, the callback of disconnection would not // be called. Therefore a separate clean-up of GATT connection is need. cleanUpGattConnection(); } } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { Bundle extras = intent.getExtras(); if (extras == null) return; final BluetoothDevice device = extras.getParcelable(BluetoothDevice.EXTRA_DEVICE); final int deviceBondState = extras.getInt(BluetoothDevice.EXTRA_BOND_STATE); Log.d(TAG, "onHandleIntent: state change on device " + device.getName() + " [" + device.getAddress() + "], bond state: " + deviceBondState); if (!isTargetKeyboard(device)) return; if (deviceBondState == BluetoothDevice.BOND_NONE) { handleGattDisconnection(); } } else if (ACTION_KEYBOARD_UPDATE_CONFIRMED.equals(action)) { dismissUpdateNotification(); if (mDfuStatus != DFU_STATE_INFO_READY || mDfuStatus == DFU_STATE_UPDATING) { Log.w(TAG, "onHandleIntent: DFP preparation not ready or DFU is in progress. "); changeDfuStatus(DFU_STATE_UPDATE_ABORTED); return; } String keyboardName = intent.getStringExtra(EXTRA_KEYBOARD_NAME); String keyboardAddress = intent.getStringExtra(EXTRA_KEYBOARD_ADDRESS); if (!mKeyboardName.equals(keyboardName) || !mKeyboardAddress.equals(keyboardAddress)) { Log.w(TAG, "onHandleIntent: No DFU service associated with " + keyboardName + " [" + keyboardAddress + "]"); return; } Log.d(TAG, "onHandleIntent: Start update process on " + keyboardName + " [" + keyboardAddress + "]"); changeDfuStatus(DFU_STATE_SWITCHING_TO_DFU_MODE); } else if (ACTION_KEYBOARD_UPDATE_POSTPONED.equals(action)) { dismissUpdateNotification(); // TODO(mcchou): Update the preference when the Settings keyboard entry is available. } }
From source file:cn.edu.zju.bme319.cordova.ExtraInfo.java
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { Activity activity = this.cordova.getActivity(); context = (Context) this.context; /*from w w w . j a v a 2 s . c o m*/ // 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(); found_devices = new ArrayList<BluetoothDevice>(); if (btadapter == null) { btadapter = BluetoothAdapter.getDefaultAdapter(); } if (action.equals("getExtra")) { callbackContext.success("123"); return true; } else 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); callbackContext.success(devicesFound); //result = new PluginResult(Status.OK, devicesFound); } catch (Exception Ex) { Log.d("BluetoothPlugin - "+ACTION_DISCOVER_DEVICES, "Got Exception "+ Ex.getMessage()); callbackContext.error("discoveryError"); //result = new PluginResult(Status.ERROR); } // try { // // Log.d("BluetoothPlugin", "We're in "+ACTION_DISCOVER_DEVICES); // // // Create a BroadcastReceiver for ACTION_FOUND //// final BroadcastReceiver mReceiver = new BroadcastReceiver() { //// 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); //// // Add the name and address to an array adapter to show in a ListView //// mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); //// } //// } //// }; //// // Register the BroadcastReceiver //// IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); //// registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy //// //// // ?? //// if (btadapter.isDiscovering()) { //// btadapter.cancelDiscovery(); //// Log.d("BluetoothPlugin", "We're in "+"12"); //// } //// //? //// Log.d("BluetoothPlugin", "We're in "+"1234"); //// btadapter.startDiscovery(); //// Log.d("BluetoothPlugin", "We're in "+"123456"); //// //// found_devices.clear(); //// //discovering=true; //// //// //if (btadapter.isDiscovering()) { //// // btadapter.cancelDiscovery(); //// //} //// //// SendCommand(0); //// //// 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); //// callbackContext.success(devicesFound); // //result = new PluginResult(Status.OK, devicesFound); // return true; // } catch (Exception Ex) { // Log.d("BluetoothPlugin - "+ACTION_DISCOVER_DEVICES, "Got Exception "+ Ex.getMessage()); // //result = new PluginResult(Status.ERROR); // callbackContext.error("discoverError"); // return false; // } } 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); callbackContext.success(""+isEnabled); //result = new PluginResult(Status.OK, isEnabled); return true; } catch (Exception Ex) { Log.d("BluetoothPlugin - "+ACTION_IS_BT_ENABLED, "Got Exception "+ Ex.getMessage()); callbackContext.error("isBTEnabledError"); //result = new PluginResult(Status.ERROR); return false; } } 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); callbackContext.success("" + enabled); //result = new PluginResult(Status.OK, enabled); return true; } catch (Exception Ex) { Log.d("BluetoothPlugin - "+ACTION_ENABLE_BT, "Got Exception "+ Ex.getMessage()); callbackContext.error("EnableBTError"); //result = new PluginResult(Status.ERROR); return false; } } 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); callbackContext.success("" + disabled); //result = new PluginResult(Status.OK, disabled); return true; } catch (Exception Ex) { Log.d("BluetoothPlugin - "+ACTION_DISABLE_BT, "Got Exception "+ Ex.getMessage()); callbackContext.error("DisableBTError"); //result = new PluginResult(Status.ERROR); return false; } } else if (ACTION_PAIR_BT.equals(action)) { try { Log.d("BluetoothPlugin", "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("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); callbackContext.success("" + paired); //result = new PluginResult(Status.OK, paired); return true; } catch (Exception Ex) { Log.d("BluetoothPlugin - "+ACTION_PAIR_BT, "Got Exception "+ Ex.getMessage()); callbackContext.error("pairBTError"); //result = new PluginResult(Status.ERROR); return false; } } else if (ACTION_UNPAIR_BT.equals(action)) { try { Log.d("BluetoothPlugin", "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("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); callbackContext.success("" + unpaired); //result = new PluginResult(Status.OK, unpaired); return true; } catch (Exception Ex) { Log.d("BluetoothPlugin - "+ACTION_UNPAIR_BT, "Got Exception "+ Ex.getMessage()); callbackContext.error("unpairBTError"); //result = new PluginResult(Status.ERROR); return false; } } 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); callbackContext.success("" + resultBoundDevices); //result = new PluginResult(Status.OK, resultBoundDevices); return true; } catch (Exception Ex) { Log.d("BluetoothPlugin - "+ACTION_LIST_BOUND_DEVICES, "Got Exception "+ Ex.getMessage()); callbackContext.error("resultBoundDevicesError"); //result = new PluginResult(Status.ERROR); return false; } } 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); callbackContext.success("" + stopped); //result = new PluginResult(Status.OK, stopped); return true; } catch (Exception Ex) { Log.d("BluetoothPlugin - "+ACTION_STOP_DISCOVERING_BT, "Got Exception "+ Ex.getMessage()); callbackContext.error("stoppedError"); //result = new PluginResult(Status.ERROR); return false; } } else if (ACTION_IS_BOUND_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in "+ACTION_IS_BOUND_BT); String addressDevice = args.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); callbackContext.success("" + state); //result = new PluginResult(Status.OK, state); return true; } catch (Exception Ex) { Log.d("BluetoothPlugin - "+ACTION_IS_BOUND_BT, "Got Exception "+ Ex.getMessage()); callbackContext.error("boundBTError"); //result = new PluginResult(Status.ERROR); return false; } } else if(ACTION_BT_CONNECT.equals(action)){ try { Log.d("BluetoothPlugin", "We're in "+ACTION_BT_CONNECT); deviceAddress = "8C:DE:52:99:26:23"; Log.d("BluetoothPlugin", "We're in "+deviceAddress); BluetoothDevice device = btadapter.getRemoteDevice(deviceAddress); //m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class }); //bluetoothSocket = (BluetoothSocket) m.invoke(device, Integer.valueOf(1)); //SendCommand(0); // ??socket try { bluetoothSocket = device.createRfcommSocketToServiceRecord(UUID .fromString(MY_UUID)); } catch (IOException e) { //Toast.makeText(this, "?", Toast.LENGTH_SHORT).show(); } bluetoothSocket.connect(); sendCommandFlag = 0; SendCommand(sendCommandFlag); if(bluetoothSocket.isConnected()) { this.isConnection = true; String str = ""; // try { inputStream = bluetoothSocket.getInputStream(); // ??? str = ""+1; } catch (IOException e) { //Toast.makeText(this, "??", Toast.LENGTH_SHORT).show(); //return; str=""+2; } if (bThread == false) { ReadThread.start(); bThread = true; str = ""+3; } else { bRun = true; str = ""+4; } //result = new PluginResult(Status.OK, str); //result.setKeepCallback(true); // callbackContext.sendPluginResult(result); callbackContext.success("" + str); } else { //result = new PluginResult(Status.OK, "failure"); callbackContext.error("Could not connect to "); } return true; } catch (Exception Ex) { // TODO: handle exception Log.d("BluetoothPlugin - "+ACTION_BT_CONNECT, "Got Exception "+ Ex.getMessage()); //result = new PluginResult(Status.ERROR); callbackContext.error("Could not connect to "); return false; } }else if(ACTION_BT_GETDATA.equals(action)){ try { Log.d("BluetoothPlugin", "We're in "+ACTION_BT_GETDATA); sendCommandFlag = 1; SendCommand(sendCommandFlag); // if (bluetoothSocket != null) { // if(bluetoothSocket.isConnected()){ // SendCommand(1); // } // } // //result = new PluginResult(Status.OK, spoValue); Log.v("Get1 ", returnBTData); while(returnBTData == "") { Log.v("Get2 ", returnBTData); } Log.v("Get3 ", returnBTData); callbackContext.success("" + returnBTData); //ReadThread.cancel(); bluetoothSocket.close(); bluetoothSocket = null; return true; } catch (Exception Ex) { // TODO: handle exception Log.d("BluetoothPlugin - "+ACTION_BT_GETDATA, "Got Exception "+ Ex.getMessage()); callbackContext.error("" + "getDataError"); //result = new PluginResult(Status.ERROR); return false; } } else { // result = new PluginResult(Status.INVALID_ACTION); // Log.d("BluetoothPlugin", "Invalid action : "+action+" passed"); // return result; callbackContext.error("" + "actionError"); } return false; }
From source file:com.zologic.tardis.app.MainActivity.java
private void startScan(final UUID[] servicesToScan, final String deviceNameToScanFor) { Log.d(TAG, "startScan"); // Stop current scanning (if needed) stopScanning();//from w w w .j a v a2 s . c om // Configure scanning BluetoothAdapter bluetoothAdapter = BleUtils.getBluetoothAdapter(getApplicationContext()); if (BleUtils.getBleStatus(this) != BleUtils.STATUS_BLE_ENABLED) { Log.w(TAG, "startScan: BluetoothAdapter not initialized or unspecified address."); } else { mScanner = new BleDevicesScanner(bluetoothAdapter, servicesToScan, new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) { final String deviceName = device.getName(); //Log.d(TAG, "Discovered device: " + (deviceName != null ? deviceName : "<unknown>")); BluetoothDeviceData previouslyScannedDeviceData = null; if (deviceNameToScanFor == null || (deviceName != null && deviceName.equalsIgnoreCase(deviceNameToScanFor))) { // Workaround for bug in service discovery. Discovery filtered by service uuid is not working on Android 4.3, 4.4 if (mScannedDevices == null) mScannedDevices = new ArrayList<>(); // Safeguard // Check that the device was not previously found for (BluetoothDeviceData deviceData : mScannedDevices) { if (deviceData.device.getAddress().equals(device.getAddress())) { previouslyScannedDeviceData = deviceData; break; } } BluetoothDeviceData deviceData; if (previouslyScannedDeviceData == null) { // Add it to the mScannedDevice list deviceData = new BluetoothDeviceData(); mScannedDevices.add(deviceData); } else { deviceData = previouslyScannedDeviceData; } deviceData.device = device; deviceData.rssi = rssi; deviceData.scanRecord = scanRecord; decodeScanRecords(deviceData); // Update device data long currentMillis = SystemClock.uptimeMillis(); if (previouslyScannedDeviceData == null || currentMillis - mLastUpdateMillis > kMinDelayToUpdateUI) { // Avoid updating when not a new device has been found and the time from the last update is really short to avoid updating UI so fast that it will become unresponsive mLastUpdateMillis = currentMillis; runOnUiThread(new Runnable() { @Override public void run() { updateUI(); } }); } } } }); // Start scanning mScanner.start(); } // Update UI updateUI(); }
From source file:com.zologic.tardis.app.MainActivity.java
private void showChooseDeviceServiceDialog(final BluetoothDevice device) { // Prepare dialog AlertDialog.Builder builder = new AlertDialog.Builder(this); String deviceName = device.getName(); String title = String.format(getString(R.string.scan_connectto_dialog_title_format), deviceName != null ? deviceName : device.getAddress()); String[] items = new String[kComponentsNameIds.length]; for (int i = 0; i < kComponentsNameIds.length; i++) items[i] = getString(kComponentsNameIds[i]); builder.setTitle(title).setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { switch (kComponentsNameIds[which]) { case R.string.scan_connectservice_info: { // Info mComponentToStartWhenConnected = InfoActivity.class; break; }//from w ww . j av a 2 s .c o m case R.string.scan_connectservice_uart: { // Uart mComponentToStartWhenConnected = UartActivity.class; break; } case R.string.scan_connectservice_pinio: { // PinIO mComponentToStartWhenConnected = PinIOActivity.class; break; } case R.string.scan_connectservice_controller: { // Controller mComponentToStartWhenConnected = ControllerActivity.class; break; } case R.string.scan_connectservice_beacon: { // Beacon mComponentToStartWhenConnected = BeaconActivity.class; break; } } if (mComponentToStartWhenConnected != null) { connect(device); // First connect to the device, and when connected go to selected activity } } }); // Show dialog AlertDialog dialog = builder.create(); dialog.show(); }