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.
Related
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
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 don't know actually it is right platform to ask this question or not.
I am using the broadcast receiver to check whether the Bluetooth device is connected or not.
using following code.
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mBG5Receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String bg5Tag="Bluetooth";
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.e("Device state",Integer.toString(device.getBondState()));
Log.i("Action is ",action);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Device is now connected
Log.d(bg5Tag,"Action connected");
Log.e("Device name ",device.getName());
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//Done searching
Log.d(bg5Tag,"Action searching");
Log.e("Device name ",device.getName());
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
//Device is about to disconnect
Log.d(bg5Tag,"Action about disconnect");
Log.e("Device name ",device.getName());
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//Device has disconnected
Log.d(bg5Tag,"Action disconnected");
Log.e("Device name ",device.getName());
}
else if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)){
Log.d(bg5Tag,"Action pairing request");
Log.e("Device name ",device.getName());
}
}
};
But when I tap on the device to pair then device disconnected automatically. But it moved to paired devices list. Why it is disconnecting?
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.
I managed to create a ListView, search for devices and show them, on click connect to the selected device, but now I want to know how to send from one phone to the other one just an int or a boolean or something like this.
It's a little game, there is a winner and a loser - so I want to compare two variables and check who won, then display it.
My code so far:
Searching
bluetooth.startDiscovery();
textview.setText("Searching, Make sure other device is available");
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
Displaying in a ListView
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device.getName() + "\n" + device.getAddress());
Log.i("BT", device.getName() + "\n" + device.getAddress());
listView.setAdapter(new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, mDeviceList));
}
}
};
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
Pairing the devices
private void pairDevice(BluetoothDevice device) {
try {
Log.d("pairDevice()", "Start Pairing...");
Method m = device.getClass().getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
Log.d("pairDevice()", "Pairing finished.");
} catch (Exception e) {
Log.e("pairDevice()", e.getMessage());
}
}
It works pretty well, both devices are paired.
Do I need a client and a server to transfer ints?
Here is some sample code from the android SDK: BluetoothChat
The key is to use a Service on both sides of the connection that both listens for incoming messages and sends outgoing messages. Then all your Activity has to worry about is interacting with the user, and telling the service to send the appropriate messages.
//METHOD FROM ACTIVITY
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
//METHOD FROM SERVICE
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED) return;
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}