@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; } }
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 } }
/** * Connects to the GATT server hosted on the Bluetooth LE device. * * @param address The device address of the destination device. * @return Return true if the connection is initiated successfully. The connection result is * reported asynchronously through the {@code * BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)} * callback. */ public boolean connect(final String address) { if (mBluetoothAdapter == null || address == null) { Log.w(TAG, "BluetoothAdapter not initialized or unspecified address."); return false; } // Previously connected device. Try to reconnect. if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) { Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection."); if (mBluetoothGatt.connect()) { mConnectionState = STATE_CONNECTING; return true; } else { return false; } } final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); if (device == null) { Log.w(TAG, "Device not found. Unable to connect."); return false; } // We want to directly connect to the device, so we are setting the autoConnect // parameter to false. mBluetoothGatt = device.connectGatt(this, false, mGattCallback); Log.d(TAG, "Trying to create a new connection."); mBluetoothDeviceAddress = address; mConnectionState = STATE_CONNECTING; return true; }
public boolean connect() { // create socket BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); BluetoothDevice device = btAdapter.getRemoteDevice(deviceInfo.getDeviceBTAddress()); try { // !!! On HTC standard variant is not working. // btSocket = device.createRfcommSocketToServiceRecord(LOGGER_SERVICE_UUID); Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}); BluetoothSocket btSocket = (BluetoothSocket) m.invoke(device, 1); setSocket(btSocket); } catch (Exception e) { writeToConsole("socket create failed: " + e.getMessage()); setSocket(null); return false; } // connect btAdapter.cancelDiscovery(); try { getSocket().connect(); writeToConsole("connected to " + deviceInfo.getDeviceName()); } catch (IOException e) { Log.e("BTCLIENT", "socket connect error", e); writeToConsole("can't connect to " + deviceInfo.getDeviceName()); safeCloseSocket(); return false; } // open communication streams return openCommunicationStreams(); }
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(); } } }
@Override public void onClick(View v) { switch (v.getId()) { case R.id.item_card: Log.e("click", mDataset.get(getAdapterPosition()).getName()); BluetoothDevice btDev = mDataset.get(getAdapterPosition()); if (btDev.getBondState() == BluetoothDevice.BOND_NONE) { Log.e("BlueToothTest", "start pair"); Boolean isBonded = false; try { isBonded = createBond(btDev); if (isBonded) { Log.e("Log", "Paired"); tvDeviceName.setTextColor(ContextCompat.getColor(activity, R.color.forest_green)); } } catch (Exception e) { e.printStackTrace(); } } else if (btDev.getBondState() == BluetoothDevice.BOND_BONDED) { Jump(); } break; } }
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(); } }
private DeviceDTO convertBluetoothToDTO(BluetoothDevice device) { DeviceDTO dto = new DeviceDTO(); dto.setName(device.getName()); dto.setMac(device.getAddress()); return dto; }
@Override public void onReceive(final Context context, final Intent intent) { final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // Skip other devices if (mBluetoothGatt == null || !device.getAddress().equals(mBluetoothGatt.getDevice().getAddress())) return; // String values are used as the constants are not available for Android 4.3. final int variant = intent.getIntExtra( "android.bluetooth.device.extra.PAIRING_VARIANT" /*BluetoothDevice.EXTRA_PAIRING_VARIANT*/, 0); Logger.d( mLogSession, "[Broadcast] Action received: android.bluetooth.device.action.PAIRING_REQUEST" /*BluetoothDevice.ACTION_PAIRING_REQUEST*/ + ", pairing variant: " + pairingVariantToString(variant) + " (" + variant + ")"); // The API below is available for Android 4.4 or newer. // An app may set the PIN here or set pairing confirmation (depending on the variant) // using: // device.setPin(new byte[] { '1', '2', '3', '4', '5', '6' }); // device.setPairingConfirmation(true); }
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; }
@Override public void getFactories(Collection<IOIOConnectionFactory> result) { try { Set<BluetoothDevice> bondedDevices = adapter_.getBondedDevices(); for (final BluetoothDevice device : bondedDevices) { if (device.getName().startsWith("IOIO")) { result.add( new IOIOConnectionFactory() { @Override public String getType() { return BluetoothIOIOConnection.class.getCanonicalName(); } @Override public Object getExtra() { return new Object[] {device.getName(), device.getAddress()}; } @Override public IOIOConnection createConnection() { return new BluetoothIOIOConnection(device); } }); } } } catch (SecurityException e) { Log.e(TAG, "Did you forget to declare uses-permission of android.permission.BLUETOOTH?"); throw e; } catch (NoClassDefFoundError e) { Log.w(TAG, "Bluetooth is not supported on this device.", e); } }
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(); } }
@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); // If it's already paired, skip it, because it's been listed // already if (device.getBondState() != BluetoothDevice.BOND_BONDED) { mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); // if (lastAdress.compareTo(device.getAddress())==0) // { setAndReturn(device.getAddress()); // } } // When discovery is finished, change the Activity title } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { setProgressBarIndeterminateVisibility(false); setTitle(R.string.select_device); if (mNewDevicesArrayAdapter.getCount() == 0) { String noDevices = getResources().getText(R.string.none_found).toString(); mNewDevicesArrayAdapter.add(noDevices); } } }
/** * 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); }
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()); }
@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); } }
protected void onPrepareDialogBuilder(android.app.AlertDialog.Builder builder) { // hook into the builder to refresh the list BluetoothAdapter bta = BluetoothAdapter.getDefaultAdapter(); Set<BluetoothDevice> pairedDevices = (bta != null) ? bta.getBondedDevices() : null; if (pairedDevices == null) { super.onPrepareDialogBuilder(builder); return; } CharSequence[] entries = new CharSequence[pairedDevices.size()]; CharSequence[] entryValues = new CharSequence[pairedDevices.size()]; int i = 0; for (BluetoothDevice dev : pairedDevices) { if (dev.getAddress() != null) { entries[i] = dev.getName(); if (entries[i] == null) entries[i] = "(null)"; entryValues[i] = dev.getAddress(); i++; } } setEntries(entries); setEntryValues(entryValues); super.onPrepareDialogBuilder(builder); }
/* package */ void handleAccessPermissionResult(Intent intent) { if (!mCheckingAccessPermission) { return; } HeadsetBase headset = mHandsfree.getHeadset(); // ASSERT: (headset != null) && headSet.isConnected() // REASON: mCheckingAccessPermission is true, otherwise resetAtState // has set mCheckingAccessPermission to false if (intent.getAction().equals(BluetoothDevice.ACTION_CONNECTION_ACCESS_REPLY)) { if (intent.getIntExtra( BluetoothDevice.EXTRA_CONNECTION_ACCESS_RESULT, BluetoothDevice.CONNECTION_ACCESS_NO) == BluetoothDevice.CONNECTION_ACCESS_YES) { BluetoothDevice remoteDevice = headset.getRemoteDevice(); if (intent.getBooleanExtra(BluetoothDevice.EXTRA_ALWAYS_ALLOWED, false)) { remoteDevice.setTrust(true); } AtCommandResult cpbrResult = processCpbrCommand(); headset.sendURC(cpbrResult.toString()); } else { headset.sendURC("ERROR"); } } mCpbrIndex1 = mCpbrIndex2 = -1; mCheckingAccessPermission = false; }
@Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder viewHolder; // General ListView optimization code. if (view == null) { view = mInflator.inflate(R.layout.listitem_device, null); viewHolder = new ViewHolder(); viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address); viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } BluetoothDevice device = mLeDevices.get(i); final String deviceName = device.getName(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); if (prefs.getString("last_connected_device_address", "").compareTo(device.getAddress()) == 0) { viewHolder.deviceName.setTextColor(ChartUtils.COLOR_BLUE); viewHolder.deviceAddress.setTextColor(ChartUtils.COLOR_BLUE); } viewHolder.deviceName.setText(deviceName); viewHolder.deviceAddress.setText(device.getAddress()); return view; }
/** * 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(Papandro.MESSAGE_DEVICE_NAME); Bundle bundle = new Bundle(); bundle.putString(Papandro.DEVICE_NAME, device.getName()); bundle.putString(Papandro.DEVICE_ADDR, device.getAddress()); 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; }
/** * 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()); } }
// 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(); }
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); } } }
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); } }
@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); } }); } }
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d(TAG, "广播接收者运行..." + action); // 查找到设备action if (BluetoothDevice.ACTION_FOUND.equals(action)) { // 得到蓝牙设备 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // 如果是已配对的则略过,已得到显示,其余的在添加到列表中进行显示 Log.d(TAG, device.toString()); if (device.getBondState() != BluetoothDevice.BOND_BONDED) { mNewDevicesAdapter.add(device); tv_new_devices.setVisibility(View.VISIBLE); // newDevices.add(device); } } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { setProgressBarIndeterminateVisibility(false); swiperefresh.setRefreshing(false); // btn_sann.setVisibility(View.VISIBLE); if (mNewDevicesAdapter.getCount() == 0) { setTitle("没有找到新设备"); Toast.makeText(DeviceListActivity.this, "没有发现新设备!", Toast.LENGTH_SHORT).show(); } else { setTitle(getString(R.string.chose_to_connect)); tv_new_devices.setVisibility(View.VISIBLE); } } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); digitalPinsButton = (Button) findViewById(R.id.button_digital_pins); analogPinsButton = (Button) findViewById(R.id.button_analog_pins); Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBTIntent, REQUEST_ENABLE_BT); BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); try { BluetoothDevice device = bluetooth.getRemoteDevice(BLUETOOTH_DEVICE_ADDRESS); Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}); clientSocket = (BluetoothSocket) m.invoke(device, 1); clientSocket.connect(); } catch (Exception e) { Log.d("BLUETOOTH", e.getMessage()); } Toast.makeText(getApplicationContext(), "CONNECTED", Toast.LENGTH_LONG).show(); }
int getConnectionState(BluetoothDevice device) { if (getCurrentState() == mDisconnected) { return BluetoothProfile.STATE_DISCONNECTED; } synchronized (this) { IState currentState = getCurrentState(); if (currentState == mPending) { if ((mTargetDevice != null) && mTargetDevice.equals(device)) { return BluetoothProfile.STATE_CONNECTING; } if ((mCurrentDevice != null) && mCurrentDevice.equals(device)) { return BluetoothProfile.STATE_DISCONNECTING; } if ((mIncomingDevice != null) && mIncomingDevice.equals(device)) { return BluetoothProfile.STATE_CONNECTING; // incoming connection } return BluetoothProfile.STATE_DISCONNECTED; } if (currentState == mConnected) { if (mCurrentDevice.equals(device)) { return BluetoothProfile.STATE_CONNECTED; } return BluetoothProfile.STATE_DISCONNECTED; } else { loge("Bad currentState: " + currentState); return BluetoothProfile.STATE_DISCONNECTED; } } }