Why am I not able to connect to device via Bluetooth android? - java

I am able to pair devices with the android studio app but I get the tag
"CouldNotConnectToSocket" even though the device is paired.
I am new to android studio so I am really stuck with where to go next.
I also get
getBluetoothService() called with no BluetoothManagerCallback
The UUID I created is:
private final static UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
Can anyone please help me?
new Thread() {
#Override
public void run() {
device = BA.getRemoteDevice(address);
try {
BTSocket = device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//BTSocket = createBluetoothSocket(device);
Log.d(TAG, "Device Connected");
BA.cancelDiscovery();
BTSocket.connect();
} catch (IOException ex) {
Log.d(TAG, "CouldNotConnectToSocket");
closeSocket(BTSocket);
}
}
}.start();

The issue I found out was that the devices I was trying to connect to send data back and forth require Bluetooth Low Energy support from the app.

Related

Android Studio: is possible to have hotspot with internet access? (Local Only Hotspot)

I'm new to Android Studio and I'm using the functionality of Local Only Hotspot to turn on and off programmatically the hotspot (found this two post for reference: How to turn on/off wifi hotspot programmatically in Android 8.0 (Oreo),How to turn on Wifi-Hotspot programmatically on Android >= 7.1 (including sharing the internet access)? .
private void turnOnHotspot() {
wifiManager.startLocalOnlyHotspot(new
WifiManager.LocalOnlyHotspotCallback()
{
#Override
public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
super.onStarted(reservation);
hotspotReservation = reservation;
String key = hotspotReservation.getWifiConfiguration().preSharedKey;
String ussid = hotspotReservation.getWifiConfiguration().SSID;
System.out.println("KEY: "+ key);
System.out.println("USSID: "+ ussid);
currentConfig = hotspotReservation.getWifiConfiguration();
System.out.println("STARTED THE HOTSPOT");
}
#Override
public void onStopped() {
super.onStopped();
System.out.println("STOPPED THE HOTSPOT");
}
#Override
public void onFailed(int reason) {
super.onFailed(reason);
System.out.println("FAILED THE HOTSPOT");
}
}, new Handler());
}
private void turnOffHotspot() {
active = false;
if (hotspotReservation != null) {
hotspotReservation.close();
System.out.println("CLOSE HOTSPOT");
}
}
But from what I gather from other older posts and documentation, this method gives a local network without internet access and a random SSID and Password that cannot be personalised.
I need to connect only one device to this hotspot to share the mobile data (to have internet access), but I didn't find anything that could have help me. Is there another alternative?

Problems with Bluetooth discovery

So I need device A (client) to connect to device B (server) and I've gotten it to work, but not in all cases. Upon opening the app, I want to allow the device to be discovered
private void enableDiscoverability() {
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
3600);
startActivity(discoverableIntent);
}
, and i set up a receiver to look for one specific device (just for now, I'm still learning how to use Bluetooth)
private final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
TextView output = findViewById(R.id.output);
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
BluetoothDevice temp = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = temp.getName();
Log.i("Device ", deviceName + " was found");
String deviceHardwareAddress = temp.getAddress();
if (deviceHardwareAddress.equalsIgnoreCase("DC:F7:56:DD:73:8F")) {
device = temp;
startClient();
}
}
}
};
So here is my problem. When device A is left on, it'll discover new devices for a little while, but it won't discover the new device B after a few minutes. Both devices should have a receiver and should be discoverable.
Is there a timeout when you're discovering devices? Would something happen to the receiver if it tried to connect but failed? I've tried to look it up, but I'm still new with Bluetooth so I wouldn't know where to begin. I'd be more than happy to post more code if need be
Yes. Every device has a discovery timeout. Best place to start is bluetooth.com, with huge amount of videos and documents. There is timeout for every activity in Bluetooth such as discovery, connection, data transmission etc.

Android - Closing specific Bluetooth socket

I'm trying to use an Android device to connect to Bluetooth devices to retrieve some information. In particular I'm trying to connect to Bluetooth headphones on this UUID:
"0000111E-0000-1000-8000-00805F9B34FB"
To do this I'm creating a socket and connecting it to the remote device this way:
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket
// because mmSocket is final.
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothSocket tmp = null;
mmDevice = device;
try {
// Get a BluetoothSocket to connect with the given BluetoothDevice.
// MY_UUID is the app's UUID string, also used in the server code.
tmp = device.createRfcommSocketToServiceRecord(UUID_HF);
} catch (IOException e) {
Log.e(TAG, "Socket's create() method failed", e);
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it otherwise slows down the connection.
bluetoothAdapter.cancelDiscovery();
try {
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and return.
try {
mmSocket.close();
} catch (IOException closeException) {
Log.e(TAG, "Could not close the client socket", closeException);
}
return;
}
// The connection attempt succeeded. Perform work associated with
// the connection in a separate thread.
manageMyConnectedSocket(mmSocket);}
It works fine when the headphones are not yet connected with my Android device. But what happens is that the headphones connect automatically with my Android device thanks to the OS itself. And in this case, when I execute the mmSocket.connect() method, it does not return. I thought that maybe Android has connected automatically another socket with the same UUID and so mine doesn't work. Do you think this is the problem? And if it is, is there a way to close all the sockets between my Android device and a remote Bluetooth device? Or maybe just the one that is bothering my process?
Thanks in advance.
what actually happens is the OS is doing the paired device criteria to save some battery as the searching process consume a lot of energy.
since you've done the search you should go for searching in paired devices not normal search and the result of the search should be taken from
Query paired devices
Before performing device discovery, it's worth querying the set of paired devices to see if the desired device is already known. To do so, call getBondedDevices(). This returns a set of BluetoothDevice objects representing paired devices. For example, you can query all paired devices and get the name and MAC address of each device, as the following code snippet demonstrates:
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
// There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
}
}
To initiate a connection with a Bluetooth device, all that's needed from the associated BluetoothDevice object is the MAC address, which you retrieve by calling getAddress(). You can learn more about creating a connection in the section about Connecting Devices.
this is the official documentation from google covering every detail about Bluetooth:
https://developer.android.com/guide/topics/connectivity/bluetooth

Issues communicating with UART header on Android Things Developer Preview 5 (RPI3)

I am attempting to communicate with a Pi header using Android Things Developer Preview 5. Below is the class I have created to communicate with the header as per the official Android Things documentation:
public class UartComm {
private static final String UART_DEVICE_NAME = "UART1";
private UartDevice mDevice;
private void configureUartFrame(UartDevice uart) throws IOException {
// Configure the UART port
uart.setBaudrate(115200);
}
public void onCreate() {
try {
PeripheralManagerService manager = new PeripheralManagerService();
List<String> deviceList = manager.getUartDeviceList();
if (deviceList.isEmpty()) {
Log.i(TAG, "No UART port available on this device.");
} else {
Log.i(TAG, "List of available devices: " + deviceList);
}
mDevice = manager.openUartDevice(UART_DEVICE_NAME);
configureUartFrame(mDevice);
mDevice.registerUartDeviceCallback(mUartCallback);
} catch (Exception e) {
Log.w(TAG, "Unable to access UART device", e);
}
}
public void readUartBuffer(UartDevice uart) throws IOException {
// Maximum amount of data to read at one time
final int maxCount = 40;
byte[] buffer = new byte[maxCount];
uart.read(buffer, maxCount);
String data = new String(buffer, "UTF-8");
Log.d(TAG, data);
}
private UartDeviceCallback mUartCallback = new UartDeviceCallback() {
#Override
public boolean onUartDeviceDataAvailable(UartDevice uart) {
// Read available data from the UART device
try {
readUartBuffer(uart);
} catch (IOException e) {
Log.w(TAG, "Unable to access UART device", e);
}
// Continue listening for more interrupts
return true;
}
#Override
public void onUartDeviceError(UartDevice uart, int error) {
Log.w(TAG, uart + ": Error event " + error);
}
};
}
In my MainActivity I create an instance of UartComm by doing UartComm device = new UartComm() and the proceed to call device.onCreate()
I have also modified /boot/cmdline.txt and removed the console=serial0,115200 and replaced it with console=tty0, I have also tried just removing the console line without adding console=tty0. In /boot/config.txt I have also removed enable_uart=1 and core-freq=400 and also added dtoverlay=pi3-miniuart-bt I have also tried to remove Bluetooth support altogether by doing dtoverlay=pi3-disable-bt to no avail.
I have tested that the header works and is configured correctly in Rapsbian, where I swapped /dev/ttyAMA0 and /dev/ttyS0 and it worked correctly. I was able to run the screen command on Raspbian with a default baud rate of 115200 and was able to get the desired information.
I would like to do the same in Android Things Developer Preview 5 and have the Bluetooth run over the mini-uart ttyS0 and the header run over ttyAMA0. My desired result is for the header to be accessible over UART0.
An older USB serial device that has the same functionality works, but I would prefer the UART device be physically on top of the Pi, so that is not an option.
Might be wrong but shouldn't:
private static final String UART_DEVICE_NAME = "UART1";
be UART0 i.e.
private static final String UART_DEVICE_NAME = "UART0";
I did a UART example here https://github.com/blundell/androidthings-uart/blob/master/app/src/main/java/com/blundell/tut/MainActivity.java (obviously different hardware) But it's connected to raspberry pi pins in the same way like so:

Bluetooth HID server accept blocking forever

I'm writing a bluetooth HID server for a small and very simple bluetooth remote. I'm following the documentation here.
My application's permission include:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
And this is my BluetoothServerSocket reading connection-accepting thread:
private class AcceptThread extends Thread {
public void run() {
BluetoothSocket socket = null;
while(true) {
try {
socket = MyBluetoothServerSocket.accept(); // problematic line
} catch(IOException e) {
Log.i(BLUETOOTH_SERVICE, e.toString());
break;
}
if(socket != null) {
readInput(socket);
try {
MyBluetoothServerSocket.close();
} catch (IOException e) {
Log.i(BLUETOOTH_SERVICE, e.toString());
}
} else {
Log.i(BLUETOOTH_SERVICE, "Could not accept a connection from the socket.\n");
}
break;
}
}
}
MyBluetoothServerSocket is a socket constructed like this:
MyBluetoothAdapter.listenUsingRfcommWithServiceRecord("MyService", UUID.fromString("00001124-0000-1000-8000-00805f9b34fb"));
The UUID I'm using above is the only one my remote control device reports through the following method:
MyBluetoothDevice.getUuids();
And MyBluetoothAdapter is just the default adapter:
BluetoothAdapter.getDefaultAdapter();
The rest of the code involved is minimal (making sure bluetooth is on, selecting the correct device) and working correctly. The remote is bonded to the phone.
The line marked as problematic in the code above (accept()) never returns i.e. it blocks forever. What am I doing wrong?
edit: I've tried MyBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord without success.
HID is based on the L2CAP bluetooth profile (protocol?), which is not implemented (line 107) in Android as of October 2013.
This makes it currently impossible to connect to a HID device.

Categories

Resources