I'm currently making an app in Android Studio that should communicate with the HC06 Bluetooth Module.
I've started with a code I found online here :
http://android-er.blogspot.com/2015/10/android-communicate-with-arduino-hc-06.html
It works but I'm trying to understand the following part (the comments are mine so it may be wrong)
private void setup() {
//store the bluetooth bonded devices in Bluetooth Devices List
Set<BluetoothDevice> PairedDevices = BluetoothAdapter.getBondedDevices();
// check if we have something in the list
if (PairedDevices.size() > 0) {
PairedDeviceArrayList = new ArrayList<BluetoothDevice>();
//add each Bluetooth Device in an array
for (BluetoothDevice device : PairedDevices) {
PairedDeviceArrayList.add(device);//put everything in a
}
PairedDeviceAdapter = new ArrayAdapter<BluetoothDevice>(this, android.R.layout.simple_list_item_1, PairedDeviceArrayList);
ListViewPairedDevice.setAdapter(PairedDeviceAdapter);
}
}
Why is the "PairedDeviceList" needed? I had the PairedDevices list that holds the Bluetooth devices.
Also, I'm not sure how an "adapter" object works, so if u could help me with some explanation it would mean a lot.
If you could find an easier way to list the devices feel free to share, please.
Thanks
Related
I'm struggling for a while with the aforementioned problem. I'd like to get a list of paired bluetooth devices (this seems to be fine by now) and being aware of what the required bluetooth module's MAC address is, simply selecting this MAC address and using it later as a parameter. I'm having troubles with trying to pick out the 30:14:10:17:06:93 address from the list.
Here is my code snippet:
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
TextView devicesInPairWithPhone = (TextView) findViewById(R.id.devicesInPairWithPhone);
devicesInPairWithPhone.setText(pairedDevices.toString());
for (BluetoothDevice device : pairedDevices) {
if (device.toString().equals("30:14:10:17:06:93")) {
mDevice = device;
textView.setText(device.toString());
}
else {
textView.setText("Selecting the correct bt module was unsuccessful.");
}
}
In this case on textView (I know, not an intuitive name, sorry for that) I get "Selecting the correct bt module was unsuccessful." all the time, i.e. the if(){} condition is never met. On devicesInPairWithPhone I get a fair set though: [30:14:10:17:06:93, 6C:0E:0D:E2:blablabla, ...]
Does someone have any idea what the problem might be? Thank you in advance!
Okay, my fault, I didn't pay attention to the fact that as the loop is iterating it will eventually print out "Selecting the correct bt module was unsuccessful." for the last element of the Set, thus this is what we will see on the screen.
I've implemented a list with all of my paired devices, and now I'd like to know if it's possible to connect to some of them only with clicking on the item.
For example if my list contains a bluetooth device called X and I want to connect to it (with my app) click on it and the connection is stablished between device and my phone.
This is how I list my paired devices :
myListView = (ListView) dialog.findViewById(R.id.BTList);
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
pairedDevices = myBluetoothAdapter.getBondedDevices();
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
If you know the name of the device you wish to pair to you can use an equals comparison.
private static final String DEVICE_WE_WANT_TO MATCH = "X";
String devName = device.getName();
if(devName.equals(DEVICE_WE_WANT_TO MATCH)){
// Connect.
}
You can also use an app UUID
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
This will mean that only devices using this UUID will connect using your protocol, it's an extra layer of security for the app.
In this, latter, case, we're relying on one android device to be acting as a BT server and the other as a BT client.
I need to "rename" bluetooth paired device of Android phone with programming. But searching results are most discuss about local bluetooth rename method. And it could use setname() to complete. Does there have any method to rename "paired device" of Android phone ?
I know the question is old, but I just needed this and found out how to do it. It uses reflexion so I'm not sure this is the best way to go but it works.
public void renamePairDevice(BluetoothDevice device, String name)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
{
Method m = device.getClass().getMethod("setAlias", String.class);
m.invoke(device, name);
}
I don't think you can rename the name of the paired device. You can only change the name from the paired device's settings.
Think of it like a wifi router, you cannot change the name of the router, but you can only connect to it.
However if you want,you could assign this way
Set<BluetoothDevice> devices = btAdapter.getBondedDevices();
if (devices.size() > 0) {
for(int i=0;i<device.size();i++) {
mDevice[i] = device;
bondedDevices.add(mDevice.getName());
}
}
That way you could get the name of the paired Devices as a mDevice array. Hope it solved your issue
After reading the dot42 comments and trolling Java examples I managed to setup a Bluetooth connection but fail to open the connection. I cannot determine the problem. I followed the docs step by step.
My target device is a HTC Explorer running on 2.3 Gingerbread. Here is my code.
//Target 2.3 (Gingerbread)
[assembly: Application("dot42Application1")]
[assembly: UsesPermission(Android.Manifest.Permission.BLUETOOTH)]
[assembly: UsesPermission(Android.Manifest.Permission.BLUETOOTH_ADMIN)]
namespace dot42Application1
{
[Activity]
public class MainActivity : Activity
{
private TextView txStatus;
protected override void OnCreate(Bundle savedInstance)
{
base.OnCreate(savedInstance);
SetContentView(R.Layouts.MainLayout);
// Find UI controls
txStatus = FindViewById<TextView>(R.Ids.txStatus);
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
var bt = BluetoothAdapter.GetDefaultAdapter();
if (bt != null) //If device has not Bluetooth this will be null
{
if (bt.IsEnabled()) //Is Bluetooth device enabled?
{
var BT_My_Addr = bt.Address; //Get the devices MAC
var BT_Bonded = bt.GetBondedDevices().ToList(); //Get a list of bonded devices- I bonded to a BT2TTL Board earlier.
txStatus.Text = BT_My_Addr + System.Environment.NewLine; //Shows my MAC on screen.
string BT_Remote_Address = string.Empty;
foreach (var BTDevice in BT_Bonded) //Just searchging for string in bonded list
{
if (BTDevice.Name.Contains("linvor"))
{
BT_Remote_Address = BTDevice.Address;
}
}
//Gets remote device
var BT_Remote_Device = bt.GetRemoteDevice(BT_Remote_Address);
//Create a RFCOMM Socket to remote device using popular UUID ofr BT Serial boards
var BTsocket = BT_Remote_Device.CreateInsecureRfcommSocketToServiceRecord(Java.Util.UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"));
//Call anyway to make sure there is no discvoerry in the backgorund. It slows stuff down.
bt.CancelDiscovery();
//Exception here? Dont know why :(
BTsocket.Connect();
//Suppsoed to dump 0 to 99999 to my listening serial device but I never get this far.
var BT_Out = BTsocket.GetOutputStream();
for (int i = 0; i < 99999; i++)
{
BT_Out.Write(Encoding.ASCII.GetBytes(i.ToString()));
}
}
else
{
txStatus.Text = "Bluetooth is disabled :(";
}
}
}
}
And this is what it shows after the socket creation
and the error...
What am I doing wrong? :(
I seem to have solved the problem by analysing various code snippets on the internet. I think the problem was trying to do everything in the OnCreate method. The steps I followed are the following:
Created a button on the main view (MainActivity.xml) and attached a onClick method.
Moved all the code OUT of the OnCreate method. (I think this allows the application to fully initialise.) Created an event handler for the button with two methods.
The two methods are the same as the code I posted in my original question. Just they are separated out and called when the user clicks the button.
findBT() Gets the default adapter. Checks if Bluetooth is enabled if not does the intent filter. Or if it is it will cycle through the bonded list and match a device name and store the BluetoohDevice in a variable. This is another thing that is different from my code. I do not use GetRemoteDevice I just assign the device from the BondedList to my global variable.
openBT() creates the RFCOMM socket (this did not work with unsecure - it threw an exception but using the secure method worked!)
You have to pair to the remote device using the Androids Bluetooth control panel. This code will not scan or connect to devices that are not paired. It will just throw null exceptions.
Also I left the target SDK 2.3.x but I am using the 4.x API.
-Disclosure. I am not a seasoned Android developer and just learning about the life cycle of Java applications in the Android context. I hope this can help other C# developers trying to do the same.
I am trying to get the list of the bonded bluetooth devices on the phone.
My problem is that I am getting it in a "non friendly" way.
Here is my code:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
ArrayList<String> listview =
new ArrayList<String>(Arrays.asList(pairedDevices.toString()));
I'm getting: 00:23:7f:5f:fe:1c...
How can i get the friendly names and not numbers?
Just to add that I know about getname(), but as I understand its only for a connected device and not for the bonded devices.
the getName() method of the BluetoothDevice device class will help you out. Just iterate through the Set and call the getName() method on each BluetoothDevice object.