I want to share the data between 2 bluetooth devices without pairing and in both the phones my app will be installed
so i used this method (https://arxiv.org/ftp/arxiv/papers/1507/1507.00650.pdf)
Bluetooth device advertises a list of services using UUIDs numbers.
This how registered a service=====>
String uuid = "f2989d52-b3d6-4205-b34d-04f35ea264e5";
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothServerSocket btSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("MYAPP", UUID.fromString(uuid))
Intents for callback===>
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter1);
IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_UUID);
registerReceiver(mReceiver, filter2);
After that i call
bluetoothAdapter.startDiscovery(); // to start discovery of devices
Code to handle intents==>
private final BroadcastReceiver mReceiver = new
BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.e("SUNIL","receiver");
String action = intent.getAction();
Log.e("SUNIL","receiver action"+action);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Boolean uuid1 = device.fetchUuidsWithSdp();
mDeviceList.add(device);
Log.e("SUNIL","device uuid result"+uuid1);
Log.e("SUNIL","device"+device.getAddress()+device.getUuids()+device.getBondState());
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
// discovery has finished, give a call to fetchUuidsWithSdp on first device in list.
if (!mDeviceList.isEmpty()) {
BluetoothDevice device = mDeviceList.remove(0);
boolean result = device.fetchUuidsWithSdp();
Log.e("SUNIL", "device uuid result223" + result+"==uuid finished"+device.getUuids());
}
}
else if (BluetoothDevice.ACTION_UUID.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.e("SUNIL","device.getUuids()"+device.getUuids());
Parcelable[] uuids = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
if(uuids != null) {
for (Parcelable ep : uuids) {
if (uuids != null) {
String uuid = ep.toString();
Log.e("SUNIL", "uuid===>" + uuid+"===="+device.getName());
**getting uuid null here**
}
}
}
}
}
};
Please help me and i am new to this bluetooth API's
I have trued with redmi 6A and redmi 6 PRO devices
Related
I am trying to discover bluetooth devices and append results to TableLayout.
Basically, I'm trying to start the discovery and print deviceName and rssi to table layout.
Here is my code:
public class DatabaseActivity extends AppCompatActivity {
public BluetoothAdapter bluetoothAdapter;
private final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress();
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
// Append to tableBLE
TableLayout tl = findViewById(R.id.tableBLE);
appendTableFront(tl, deviceName + "_" + rssi);
Log.d("PBK_Test - Detected", deviceName + "_" + rssi);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
// Bluetooth
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
}
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 0);
}
// Start Discovery
bluetoothAdapter.startDiscovery();
// Register for broadcasts when a device is discovered.
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
// Make discoverable
if (bluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
public void appendTableFront(TableLayout tl, String msg) {
TableRow newRow = new TableRow(this);
newRow.setBackgroundColor(Color.GRAY);
newRow.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
TextView label_id = new TextView(this);
label_id.setText(msg);
label_id.setTextColor(Color.WHITE);
label_id.setPadding(5, 5, 5, 5);
newRow.addView(label_id);
tl.addView(newRow);
}
}
I can become discoverable, but not detecting other devices.
I tried the built-in bluetooth discovery and it works fine.
Edit:
I added Log.d("PBK_Test - Detected", deviceName + "_" + rssi); to onReceive and it is not shown as well.
newRow might be null, because there's no final keyword and you change the scope.
Remove this instruction: runOnUiThread() ...because it's not running in the background.
I figured it out myself.
The problem is not in the code --
You have to get into Settings -> App -> <app_name> -> Permissions, to manually give your app permissions, EVEN IF YOU HAVE DECLARED THEM IN MANIFEST.
Citation:
This video https://www.youtube.com/watch?v=dLZDJgblgj8
I want to implement passkey for connect device or establish the connection with BLE device. I have 6 byte passkey, So how we will create bond or pairing and send passkey to the BLE device using RxAndroid library.
Can any one give me reference or document link or demo link for implementation of Passkey or create bond or pairing while establish connection.
Thanks in advance!!
First you need to find the nearby devices.
public void registerDeviceForAnyNEwDeviceFound() {
// Register for broadcasts when a device is discovered.
mBluetoothAdapter.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mSearchReceiver, filter);
Log.e("STATUS", "" +
mBluetoothAdapter.isDiscovering());
isSearchReceiverRegistered = true;
}
// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver mSearchReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e("SEARCH STARTED", "TRUE");
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
try {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
Device mDevice = new Device();
mDevice.setDeviceName(deviceName);
mDevice.setDeviceAddress(deviceHardwareAddress);
mDevice.setmBluetoothDevice(device);
Log.e("Discovered DEVICE", deviceName);
Log.e("BOND STATE", "" + device.getBondState());
nearbyDeviceList.add(mDevice);
mNearbyDeviceRecAdapter.notifyDataSetChanged();
} catch (Exception e) {
Log.e("EXCEPTION", e.getLocalizedMessage());
}
}
}
};
Then you need to register another BroadCastReceiver, this receiver will listen to the bond changes with the device with whom you are going to pair with.
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mPairingReceiver, filter);
private final BroadcastReceiver mPairingReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//3 cases:
//case1: bonded already
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
Log.d(TAG, "BroadcastReceiver: BOND_BONDED.");
Log.e(TAG, "BroadcastReceiver: BOND_BONDED." + mDevice.getName());
mBluetoothAdapter.cancelDiscovery();
}
//case2: creating a bone
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
Log.e(TAG, "BroadcastReceiver: BOND_BONDING." + mDevice.getName());
}
//case3: breaking a bond
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
Log.e(TAG, "BroadcastReceiver: BOND_NONE." + mDevice.getName());
}
}
}
};
Finally when you want to pair with the device call:
mNearbyDeviceRecAdapter.getItemAtPosition(position).getmBluetoothDevice().createBond();
Once you call this statement, this will initiate pairing with the device.
Hope! this helps.
I've searched and tried everything I could, but I just can't get this to work. From all the examples I've seen, I seem to be doing the right thing, but maybe I'm missing something.
I'm trying to discover Bluetooth devices on Android and have been following the guide on the Android Developer page: http://developer.android.com/guide/topics/connectivity/bluetooth.html
I can enable BT when the app starts and get the name and address of my device. However, I can't see the names of other nearby devices (supposed to show up as a toast). The intriguing part is, when I enable BT before starting the app, it actually does what I want and shows the nearby devices' name.
Here's the code:
public class MainActivity extends AppCompatActivity {
TextView mTextView;
BluetoothAdapter mBluetoothAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
final String status;
// Check BT support
if (mBluetoothAdapter == null){
// Device does not support BT
status = "Your device does not support Bluetooth";
}
else {
String myAddress = mBluetoothAdapter.getAddress();
String myName = mBluetoothAdapter.getName();
status = myName + ": " + myAddress;
}
mTextView = (TextView)findViewById(R.id.textView);
// If BT is enabled before app start, discover devices
// This is where things work, for some reason
if (mBluetoothAdapter.isEnabled()){
mTextView.setText(status);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver, filter);
getBTdevices();
}
// If BT is not enabled, enable it and look for devices
else{
mTextView.setText(status);
mBluetoothAdapter.enable();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver, filter);
getBTdevices();
}
}
protected void getBTdevices(){
// Stop discovery and start
if (mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
}
private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TextView textView = (TextView)findViewById(R.id.textView2);
textView.setText("Start");
String action = intent.getAction();
// If device is found
if (BluetoothDevice.ACTION_FOUND.equals(action)){
// Get BT device from intent
textView.setText("Device found");
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(context, "Device found: "+ device.getName(), Toast.LENGTH_LONG).show();
System.out.println("Discovered!");
}
}
};
protected void onDestroy(){
super.onDestroy();
if (mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
unregisterReceiver(mBroadcastReceiver);
}
}
Some help would really be appreciated, I don't know what else I can do.
EDIT: Forgot to mention, I have set both the BLUETOOTH and BLUETOOTH_ADMIN permissions in the manifest.
The bluetooth scan should stop as soon as it finds a device of choice, and then after stopping it should start again, when i do the following, i get error saying the app has stopped. i want to scan for 3 times, and store their radiuses.
private BluetoothAdapter mBtAdapter;
mBtAdapter.startDiscovery();
//this string stores the MAC Address of the required device
string name = "12:34:D3:s3:we";
private final BroadcastReceiver mReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
if(device.getAddress.equals(name)){
mBtAdapter.cancelDiscovery();
}
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
{
mBtAdapter.startDiscovery();
}
}
}
I am having a problem with my broadcast receiver and finding a particular device. Earlier in my program, I look for the current devices and allow the user to pick on. That name and address is saved off. When the application processes its "onResume", I create a broadcast receiver.
All I am attempting to do is see if the previously saved device is in the area. It doesn't have to be paired, but must at least be seen. I don't see any of these toast messages. I have even attempted to put the device into discover-able mode prior to this.
Here is my broadcast receiver.
mBluetoothReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
try {
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);
String deviceName = device.getName();
String deviceAddress = device.getAddress();
Toast toast = Toast.makeText(getApplicationContext(), "BT Found", Toast.LENGTH_LONG);
toast.show();
if (deviceAddress.equals(mDeviceAddress)) {
Toast toasty = Toast.makeText(getApplicationContext(), "Correct BT Device Found", Toast.LENGTH_LONG);
toasty.show();
}
}
if(BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceAddress = device.getAddress();
Toast toast = Toast.makeText(getApplicationContext(), "BT Connected", Toast.LENGTH_LONG);
toast.show();
if (deviceAddress.equals(mDeviceAddress)) {
Toast toasty = Toast.makeText(getApplicationContext(), "Correct BT Device Connected", Toast.LENGTH_LONG);
toasty.show();
}
}
} catch (Exception e) {
System.out.println("Broadcast Error : " + e.toString());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mBluetoothReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mBluetoothReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
this.registerReceiver(mBluetoothReceiver, filter);
filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
this.registerReceiver(mBluetoothReceiver, filter);
filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
this.registerReceiver(mBluetoothReceiver, filter);
filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mBluetoothReceiver, filter);
Edit
It seems that the connected and disconnection events are being detected properly. They are only detected on change. However, the ACTION_FOUND is not. I cannot simply be in the area of the device.