@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_ENABLE_BT: if (resultCode == RESULT_OK) { // doDiscovery(); Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); for (BluetoothDevice device : pairedDevices) { mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } else { findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); String noDevices = getResources().getText(R.string.none_paired).toString(); mPairedDevicesArrayAdapter.add(noDevices); } } else { Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show(); finish(); } break; default: break; } }
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) { // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE); mNewDevicesArrayAdapter.add( device.getName() + "\n" + "RSSI = " + rssi + "\n" + device.getAddress()); // log for test if (device.getName().equals("Zhenan")) { DataLogger dl = new DataLogger(device.getName(), device.getAddress(), rssi.intValue()); } // When discovery is finished, change the Activity title } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { setProgressBarIndeterminateVisibility(false); setTitle(R.string.scan_finish); if (mNewDevicesArrayAdapter.getCount() == 0) { String noDevices = getResources().getText(R.string.none_found).toString(); mNewDevicesArrayAdapter.add(noDevices); } } }
public static PortInfo[] getPorts() { System.out.println("Starting Bluetooth Detection and Device Pairing"); BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { Log.w("ComPort", "Bluetooth not supported."); PortInfo[] BTDeviceSet = new PortInfo[1]; BTDeviceSet[0] = new PortInfo("", "No Devices paired :-("); return BTDeviceSet; } Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); PortInfo[] BTDeviceSet = new PortInfo[pairedDevices.size()]; Log.v("ComPort", "Anzahl paired devices: " + pairedDevices.size()); // If there are paired devices if (pairedDevices.size() > 0) { // Loop through paired devices int i = 0; for (BluetoothDevice device : pairedDevices) { // Add the name and address to an array adapter to show in a // ListView Log.d( "OOBD:BluetoothIntiWorker", "Found Bluetooth Device: " + device.getName() + "=" + device.getAddress()); BTDeviceSet[i] = new PortInfo(device.getAddress(), device.getName()); i++; } } return BTDeviceSet; }
public void run() { InputStream inStream = null; OutputStream outStream = null; mBluetoothAdapter.cancelDiscovery(); try { mySocket.connect(); } catch (IOException e) { Log.e("Bluetooth", mDevice.getName() + ": Could not establish connection with device"); try { mySocket.close(); } catch (IOException e1) { Log.e("Bluetooth", mDevice.getName() + ": could not close socket", e1); } } String line = ""; try { inStream = mySocket.getInputStream(); outStream = mySocket.getOutputStream(); outStream.write(message.getBytes()); outStream.flush(); Log.e("Bluetooth", "Message sent: " + message); inStream.close(); outStream.close(); cancel(); } catch (IOException e) { e.printStackTrace(); } }
/** * Start the ConnectedThread to begin managing a Bluetooth connection * * @param socket The BluetoothSocket on which the connection was made * @param device The BluetoothDevice that has been connected */ public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) { TopoDroidLog.Log(TopoDroidLog.LOG_SYNC, "sync connected. remote device " + device.getName()); mRemoteDevice = device; mConnectRun = true; if (mConnectingThread != null) { mConnectingThread.cancel(); mConnectingThread = null; } if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } // ONE-TO-ONE // if ( mAcceptThread != null ) { mAcceptThread.cancel(); mAcceptThread = null; } mConnectedThread = new ConnectedThread(socket); mConnectedThread.start(); Message msg = mHandler.obtainMessage(MESSAGE_DEVICE); Bundle bundle = new Bundle(); bundle.putString(DEVICE, mRemoteDevice.getName()); msg.setData(bundle); mHandler.sendMessage(msg); setConnectState(STATE_CONNECTED); }
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (BluetoothDevice.ACTION_FOUND.equals(action)) { Toast.makeText( getApplicationContext(), "Device found" + device.getName(), Toast.LENGTH_SHORT) .show(); // Device found if (device.getName().equals("SM-T325")) { visits++; ((TextView) findViewById(R.id.textView)) .setText("Number of visits this month: " + MainActivity.visits + " times"); } } else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) { Toast.makeText(getApplicationContext(), "Action connected", Toast.LENGTH_SHORT) .show(); // Device is now connected } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { Toast.makeText(getApplicationContext(), "Discovery finished", Toast.LENGTH_SHORT) .show(); // Done searching } else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) { Toast.makeText(getApplicationContext(), "Disconnect Requested", Toast.LENGTH_SHORT) .show(); // Device is about to disconnect } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) { Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_SHORT) .show(); // Device has disconnected } }
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d(TAG, "进入广播:" + action.toString()); // 发现设备 if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Log.d(TAG, "发现设备"); devices.add(device.getName() + "\n" + device.getAddress()); Log.d(TAG, "devices:" + device.getName() + "[" + device.getAddress() + "]"); // 添加非配对设备 if (isLock(device)) { String address = device.getAddress(); devices.add(device.getName() + "\n" + device.getAddress()); Log.d(TAG, "devices" + devices); deviceList.add(device); Log.d(TAG, "deviceList" + deviceList); Log.d(TAG, "address" + address); device1 = adapter.getRemoteDevice(address); Log.d(TAG, "device1:" + device1); blueclient.nativeInit(device); } } }
@Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { int minor = getMinor(scanRecord); if (doWeWantThisDevice(scanRecord)) { TextView text = null; switch (minor) { case BEACON_MINOR_1: text = (TextView) findViewById(R.id.text1); distance1 = (float) calculateDistance(-70, rssi); text.setText(device.getName() + ": " + distance1 + "m."); break; case BEACON_MINOR_2: text = (TextView) findViewById(R.id.text2); distance2 = (float) calculateDistance(-70, rssi); text.setText(device.getName() + ": " + distance2 + "m."); break; case BEACON_MINOR_3: text = (TextView) findViewById(R.id.text3); distance3 = (float) calculateDistance(-70, rssi); text.setText(device.getName() + ": " + distance3 + "m."); break; } } }
private DeviceSupport createBTDeviceSupport(String deviceAddress) throws GBException { if (mBtAdapter != null && mBtAdapter.isEnabled()) { GBDevice gbDevice = null; DeviceSupport deviceSupport = null; try { BluetoothDevice btDevice = mBtAdapter.getRemoteDevice(deviceAddress); if (btDevice.getName() == null || btDevice .getName() .startsWith("MI")) { // FIXME: workaround for Miband not being paired gbDevice = new GBDevice(deviceAddress, "MI", DeviceType.MIBAND); deviceSupport = new ServiceDeviceSupport( new MiBandSupport(), EnumSet.of( ServiceDeviceSupport.Flags.THROTTLING, ServiceDeviceSupport.Flags.BUSY_CHECKING)); } else if (btDevice.getName().indexOf("Pebble") == 0) { gbDevice = new GBDevice(deviceAddress, btDevice.getName(), DeviceType.PEBBLE); deviceSupport = new ServiceDeviceSupport( new PebbleSupport(), EnumSet.of(ServiceDeviceSupport.Flags.BUSY_CHECKING)); } if (deviceSupport != null) { deviceSupport.setContext(gbDevice, mBtAdapter, mContext); return deviceSupport; } } catch (Exception e) { throw new GBException(mContext.getString(R.string.cannot_connect_bt_address_invalid_, e)); } } return null; }
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // 查找到设备action if (BluetoothDevice.ACTION_FOUND.equals(action)) { // 得到蓝牙设备 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // 如果是已配对的则略过,已得到显示,其余的在添加到列表中进行显示 if (device.getBondState() != BluetoothDevice.BOND_BONDED) { mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } else { // 添加到已配对设备列表 mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); // mPairedDevicesArrayAdapter.add(mBtAdapter.getRemoteDevice(device.getAddress()).getName() + "\n" + device.getAddress()); } // 搜索完成action } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { setProgressBarIndeterminateVisibility(false); setTitle(getResources().getString(R.string.select)); if (mNewDevicesArrayAdapter.getCount() == 0) { String noDevices = getResources().getString(R.string.nonewdevice); mNewDevicesArrayAdapter.add(noDevices); } } }
private void stopScan() { Log.wtf(TAG, "Stopping scan : " + found); found = false; mBluetoothAdapter.stopLeScan(this); setProgressBarIndeterminateVisibility(false); for (BluetoothDevice x : mDevices) { if (x.getName() == null) { } else if (x.getName().equalsIgnoreCase(deviceName) && !found) { found = true; Log.wtf(TAG, "Device name is: " + deviceName); Log.wtf(TAG, "Device name is: " + "CONNECTING!!!!!"); if (!leManager.isConnected()) { leManager.setDevice(x); Log.wtf(TAG, "Device name is: " + "CONNECT!!!!!"); leManager.connectDevice(4); } // BluetoothDevice device = x; // currentDevice = device; // mConnectedGatt = device.connectGatt(this, true, mGattCallback); // mConnectedGatt.requestConnectionPriority(1); // Display progress UI // mHandler.sendMessage(Message.obtain(null, MSG_PROGRESS, "Connecting to " + // device.getName() + "...")); } } if (!found && stillRunning && !leManager.isConnected()) { if (!isScanRunning) { Log.wtf(TAG, "Restarting scan"); runOnUiThread(mStartRunnable); } } }
@Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_feature_dfu); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); isBLESupported(); setGUI(); // Try to create sample files if (FileHelper.newSamplesAvailable(this)) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { FileHelper.createSamples(this); } else { final DialogFragment dialog = PermissionRationaleFragment.getInstance( R.string.permission_sd_text, Manifest.permission.WRITE_EXTERNAL_STORAGE); dialog.show(getSupportFragmentManager(), null); } } // restore saved state mFileType = DfuService.TYPE_AUTO; // Default if (savedInstanceState != null) { mFileType = savedInstanceState.getInt(DATA_FILE_TYPE); mFileTypeTmp = savedInstanceState.getInt(DATA_FILE_TYPE_TMP); mFilePath = savedInstanceState.getString(DATA_FILE_PATH); mFileStreamUri = savedInstanceState.getParcelable(DATA_FILE_STREAM); mInitFilePath = savedInstanceState.getString(DATA_INIT_FILE_PATH); mInitFileStreamUri = savedInstanceState.getParcelable(DATA_INIT_FILE_STREAM); mSelectedDevice = savedInstanceState.getParcelable(DATA_DEVICE); mStatusOk = mStatusOk || savedInstanceState.getBoolean(DATA_STATUS); mUploadButton.setEnabled(mSelectedDevice != null && mStatusOk); } final Intent intent = getIntent(); mbluetoothLeDevice = intent.getParcelableExtra(BLEDeviceActivity.EXTRA_DEVICE); mBleDeviceType = intent.getIntExtra(BLEDeviceActivity.EXTRA_BLE_DEVICE_TYPE, 0xff); if (mBleDeviceType == SentekBLEDeviceType.Dongle_DFU.ordinal()) { swapDFU_UUID(true); } else if (mBleDeviceType == SentekBLEDeviceType.Probe_DFU.ordinal()) { swapDFU_UUID(false); } if (mbluetoothLeDevice != null) { mSelectedDevice = mbluetoothLeDevice.getDevice(); mUploadButton.setEnabled(mStatusOk); mDeviceNameView.setText( mSelectedDevice.getName() != null ? mSelectedDevice.getName() : getString(R.string.sentek_dfu)); } FileHelper.createSamplesNew(this); mFileType = mFileTypeTmp = DfuService.TYPE_APPLICATION; updateFileInfoNew(false); // TODO: // doUpload(true); }
/** * Called when the activity is first created. * * @param savedInstanceState If the activity is being re-initialized after previously being shut * down then this Bundle contains the data it most recently supplied in * onSaveInstanceState(Bundle). <b>Note: Otherwise it is null.</b> */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { // Device does not support Bluetooth } if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } BluetoothDevice mmDevice = null; List<String> mArray = new ArrayList<String>(); Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.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 if (device.getName().equals(deviceName)) mmDevice = device; mArray.add(device.getName() + "\n" + device.getAddress()); } } // Creating the socket. BluetoothSocket mmSocket; BluetoothSocket tmp = null; UUID myUUID = UUID.fromString(mUUID); try { // MY_UUID is the app's UUID string, also used by the server code tmp = mmDevice.createRfcommSocketToServiceRecord(myUUID); } catch (IOException e) { } mmSocket = tmp; // socket created, try to connect try { mmSocket.connect(); } catch (IOException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } // Run the example JArduino arduino = new BlinkAndAnalog(mmSocket); arduino.runArduinoProcess(); Log.i(TAG, "onCreate"); setContentView(R.layout.main); }
public GBDevice toSupportedDevice(BluetoothDevice device) { GBDeviceCandidate candidate = new GBDeviceCandidate(device, GBDevice.RSSI_UNKNOWN); if (coordinator != null && coordinator.supports(candidate)) { return new GBDevice(device.getAddress(), device.getName(), coordinator.getDeviceType()); } for (DeviceCoordinator coordinator : getAllCoordinators()) { if (coordinator.supports(candidate)) { return new GBDevice(device.getAddress(), device.getName(), coordinator.getDeviceType()); } } return null; }
/** * Connects to an device * * @param data * @param secure */ private void connectDevice(Intent data, boolean secure) { // Get the device MAC address String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS); // Get the BluetoothDevice object BluetoothDevice device = _bluetoothAdapter.getRemoteDevice(address); if (D) Log.i(TAG, "I would like to connect to " + device.getName() + " at " + device.getAddress()); // Attempt to connect to the device _chatService.connect(device, secure); _connectedToString = getString(R.string.title_connected_to, device.getName()); }
private boolean connect(View view) { if (D) Log.d(TAG, "Establishing connection to: " + btDevice.getName()); try { btSocket = btDevice.createRfcommSocketToServiceRecord(SPP_UUID); btSocket.connect(); Toast.makeText(this, "Connected to: " + btDevice.getName(), Toast.LENGTH_LONG).show(); return true; } catch (IOException e) { Toast.makeText(this, "Failed to connect to: " + btDevice.getName(), Toast.LENGTH_LONG).show(); Log.e(TAG, e.getLocalizedMessage()); } return false; }
@Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { if (!getServiceUuids(scanRecord).contains(JUMA_SERVICE_UUID)) return; if (name == null || name.equals("") || name.equals(device.getName())) { callback.onDiscover( new JumaDevice( context, ScanHelper.this, device.getName(), UUID.fromString(IDEncrypt(device.getAddress(), context))), rssi); } }
/** Connect to the picked device */ private void connect() { if (mPickedDevice == null) { showMessage( getString(R.string.error_connect, mPickedDevice.getName(), mPickedDevice.getAddress())); return; } mPickedDeviceGatt = mPickedDevice.connectGatt(this, false, mGattCallback); if (mPickedDeviceGatt == null) { showMessage( getString(R.string.error_connect, mPickedDevice.getName(), mPickedDevice.getAddress())); } }
/** * Start the ConnectedThread to begin managing a Bluetooth connection * * @param socket The BluetoothSocket on which the connection was made * @param device The BluetoothDevice that has been connected */ public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) { 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; } // Cancel the accept thread because we only want to connect to one device if (mAcceptThread != null) { mAcceptThread.cancel(); mAcceptThread = 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 // mHandler.obtainMessage(),Returns a new Message from the global message pool, and // also sets the what member of the returned Message. // 為msg 貼上what的tag Message msg = mHandler.obtainMessage(MainService.MESSAGE_DEVICE_NAME); Log.i(TAG, "device.getName() : " + device.getName()); DeviceMappingAdapter deviceMappingAdapter = new DeviceMappingAdapter(mainContext); String deviceSn = deviceMappingAdapter.getDeviceSnById(device.getName()); if (deviceSn != null) { Log.i(TAG, "泰博跑到陽明血壓計"); setState(STATE_LISTEN); mHandler.obtainMessage(MainService.MESSAGE_CONNECTION_CLOSE, 1, -1).sendToTarget(); } else { Bundle bundle = new Bundle(); bundle.putString(MainService.DEVICE_NAME, device.getName()); msg.setData(bundle); mHandler.sendMessage(msg); setState(STATE_CONNECTED); } }
public boolean attemptToCreateNewConnection(BluetoothDevice bluetoothDevice, Context context) { try { this.bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(MY_UUID); Log.e(PASS, "Succeed createRfcommSocketToServiceRecord()"); } catch (IOException e) { Log.e( FAIL, "Failed to createRfcommSocketToServiceRecord() in BluetoothManager => attemptToCreateNewConnection()"); e.printStackTrace(); return false; } try { this.bluetoothSocket.connect(); createObjectStreams(); } catch (IOException e) { Log.e(NOTE, "Could not connect over BT socket"); startBTServer(); if (this.bluetoothSocket == null) return false; } sendPubKey(context); String pubKey = new Integer(getPubKey()).toString(); storeConnection(pubKey, bluetoothDevice.getName(), bluetoothDevice.getAddress()); return true; }
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); bluetoothImage.setBackgroundResource(R.drawable.discovering_animation); anim = (AnimationDrawable) bluetoothImage.getBackground(); if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) { discoverBT.setText(R.string.cancel_discovery); enableBT.setEnabled(false); checkBT.setEnabled(false); anim.start(); Toast.makeText(MainActivity.this, R.string.discovering, Toast.LENGTH_SHORT).show(); } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { discoverBT.setText(R.string.discover_devices); enableBT.setEnabled(true); checkBT.setEnabled(true); anim.stop(); bluetoothImage.setBackground(getResources().getDrawable((R.drawable.btooth_on))); Toast.makeText(MainActivity.this, R.string.discovery_finished, Toast.LENGTH_SHORT) .show(); } else if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (!tmpBtChecker.contains(device)) { tmpBtChecker.add(device); discoveredDevicesArList.add(device.getName() + "\n" + device.getAddress()); adapterForDiscoveredDevices.notifyDataSetChanged(); } } }
/** * Busca todos os dispositivos Bluetooth pareados com o device * * @param callbackContext */ protected void getBluetoothPairedDevices(CallbackContext callbackContext) { BluetoothAdapter mBluetoothAdapter = null; try { mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { callbackContext.error(this.getErrorByCode(1)); return; } if (!mBluetoothAdapter.isEnabled()) { Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); this.mCordova.getActivity().startActivityForResult(enableBluetooth, 0); } Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { JSONArray json = new JSONArray(); for (BluetoothDevice device : pairedDevices) { Hashtable map = new Hashtable(); map.put("type", device.getType()); map.put("address", device.getAddress()); map.put("name", device.getName()); JSONObject jObj = new JSONObject(map); json.put(jObj); } callbackContext.success(json); } else { callbackContext.error(this.getErrorByCode(2)); } } catch (Exception e) { Log.e(LOG_TAG, e.getMessage()); e.printStackTrace(); callbackContext.error(e.getMessage()); } }
void checkBlue() // CHECK BLUE { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) // check id your phone has a blue antenna { Toast.makeText(ThibJackMario.this, "You do not got Bluetooth!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ThibJackMario.this, "You got Bluetooth!", Toast.LENGTH_SHORT).show(); } if (!bluetoothAdapter .isEnabled()) // check if the antenna is on or not, if not it asks you if you want to put it // on { Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBluetooth, REQUEST_CODE_ENABLE_BLUETOOTH); } devices = bluetoothAdapter.getBondedDevices(); for (BluetoothDevice blueDevice : devices) // get the list of known blue device { Toast.makeText(ThibJackMario.this, "Device = " + blueDevice.getName(), Toast.LENGTH_SHORT) .show(); } /* Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300); startActivity(discoverableIntent);*/ Toast.makeText(ThibJackMario.this, "Device = " + devices, Toast.LENGTH_SHORT).show(); }
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // ada device baru if (BluetoothDevice.ACTION_FOUND.equals(action)) { // ambil objek BluetoothDevice dari Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); arrayPairedDevices.add(device); // tulis nama dan MAC address ke ListView adapter.add("Baru:" + device.getName() + "\n" + device.getAddress()); // refresh listview, JANGAN LUPA!! adapter.notifyDataSetChanged(); } else // mulai proses discovery, untuk debug saja, memastikan proses dimulai if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) { Toast toast = Toast.makeText( getApplicationContext(), "Mulai proses discovery", Toast.LENGTH_LONG); toast.show(); } else // mulai proses discovery, untuk debug saja, memastikan proses dimulai if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { Toast toast = Toast.makeText( getApplicationContext(), "Proses discovery selesai", Toast.LENGTH_LONG); toast.show(); } }
@Override public void onResume() { super.onResume(); // *************** checkBTState(); textView1 = (TextView) findViewById(R.id.connecting); textView1.setTextSize(40); textView1.setText(" "); // Initialize array adapter for paired devices mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name); // Find and set up the ListView for paired devices ListView pairedListView = (ListView) findViewById(R.id.paired_devices); pairedListView.setAdapter(mPairedDevicesArrayAdapter); pairedListView.setOnItemClickListener(mDeviceClickListener); // Get the local Bluetooth adapter mBtAdapter = BluetoothAdapter.getDefaultAdapter(); // Get a set of currently paired devices and append to 'pairedDevices' Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices(); // Add previosuly paired devices to the array if (pairedDevices.size() > 0) { findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); // make title viewable for (BluetoothDevice device : pairedDevices) { mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } else { String noDevices = getResources().getText(R.string.none_paired).toString(); mPairedDevicesArrayAdapter.add(noDevices); } }
private void initializeUIElements() { TextView textViewDeviceName = (TextView) findViewById(R.id.textViewDeviceName); textViewDeviceName.setText(device.getName()); ImageView imageViewPairStatus = (ImageView) findViewById(R.id.imageViewPairStatus); switch (device.getBondState()) { case BluetoothDevice.BOND_NONE: imageViewPairStatus.setImageResource(R.drawable.bluetooth_notpaired); break; case BluetoothDevice.BOND_BONDED: imageViewPairStatus.setImageResource(R.drawable.bluetooth_paired); break; case BluetoothDevice.BOND_BONDING: imageViewPairStatus.setImageResource(R.drawable.bluetooth_bonding); break; } TextView textViewStatus = (TextView) findViewById(R.id.textViewStatus); switch (device.getBondState()) { case BluetoothDevice.BOND_BONDED: textViewStatus.setText(R.string.label_status_bonded); break; case BluetoothDevice.BOND_BONDING: textViewStatus.setText(R.string.label_status_bonding); break; case BluetoothDevice.BOND_NONE: textViewStatus.setText(R.string.label_status_not_bonded); break; } TextView textViewAddress = (TextView) findViewById(R.id.textViewAddress); textViewAddress.setText( getResources().getString(R.string.label_device_address) + " " + device.getAddress()); }
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) { // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // If it's already paired, skip it, because it's been listed already if (device.getBondState() != BluetoothDevice.BOND_BONDED) { String strNoFound = getIntent().getStringExtra("no_devices_found"); if (strNoFound == null) strNoFound = "No devices found"; if (mPairedDevicesArrayAdapter.getItem(0).equals(strNoFound)) { mPairedDevicesArrayAdapter.remove(strNoFound); } mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } // When discovery is finished, change the Activity title } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { setProgressBarIndeterminateVisibility(false); String strSelectDevice = getIntent().getStringExtra("select_device"); if (strSelectDevice == null) strSelectDevice = "Select a device to connect"; setTitle(strSelectDevice); } }
/** * Start the ConnectedThread to begin managing a Bluetooth connection * * @param socket The BluetoothSocket on which the connection was made * @param device The BluetoothDevice that has been connected */ public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) { 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; } // Cancel the accept thread because we only want to connect to one device if (mAcceptThread != null) { mAcceptThread.cancel(); mAcceptThread = 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(BluetoothChat.MESSAGE_DEVICE_NAME); Bundle bundle = new Bundle(); bundle.putString(BluetoothChat.DEVICE_NAME, device.getName()); msg.setData(bundle); mHandler.sendMessage(msg); setState(STATE_CONNECTED); }
@Override public void onLeScan( final BluetoothDevice device, final int rssi, final byte[] scanRecord) { // if (true) { if (device.getName().contains("SensorTag") || device.getAddress().contains("D0")) { if (onScanListener != null) { onScanListener.onScan(device, rssi, scanRecord); } System.out.println("scan info:"); System.out.println("rssi=" + rssi); System.out.println("ScanRecord:"); for (byte b : scanRecord) System.out.printf("%02X ", b); System.out.println(""); ((Activity) context) .runOnUiThread( new Runnable() { @Override public void run() { Message msg = new Message(); BluetoothScanInfo info = new BluetoothScanInfo(); info.device = device; info.rssi = rssi; info.scanRecord = scanRecord; msg.obj = info; mHandler.sendMessage(msg); } }); } }
// Start device discover with the BluetoothAdapter private void doDiscovery() { if (D) Log.d(TAG, "doDiscovery()"); // Remove all element from the list mPairedDevicesArrayAdapter.clear(); // If there are paired devices, add each one to the ArrayAdapter if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } else { String strNoFound = getIntent().getStringExtra("no_devices_found"); if (strNoFound == null) strNoFound = "No devices found"; mPairedDevicesArrayAdapter.add(strNoFound); } // Indicate scanning in the title String strScanning = getIntent().getStringExtra("scanning"); if (strScanning == null) strScanning = "Scanning for devices..."; setProgressBarIndeterminateVisibility(true); setTitle(strScanning); // Turn on sub-title for new devices // findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE); // If we're already discovering, stop it if (mBtAdapter.isDiscovering()) { mBtAdapter.cancelDiscovery(); } // Request discover from BluetoothAdapter mBtAdapter.startDiscovery(); }