I'm new to java / object oriented language and wanted to get some help on the syntax.
I have a class defined in ConnectThread.java as
public class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
tmp = device.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(mmSocket);
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
From here I tried to create a thread and connect this thread by writing this code in my connect method:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice targetdevice;
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0)
{
// Loop through paired devices
for (BluetoothDevice device : pairedDevices)
{
if (device.getName().equals("HC-06"))
targetdevice = device;
}
}
Thread writeThread = new Thread();
writeThread.ConnectThread(targetdevice);
I get the error in the last line and it says "The method ConnectThread(BluetoothDevice) is undefined for the type Thread"
I thought since ConnectThread is an extended class of Thread, I could use the methods under it. Is this not the case? What would be the right way to go about doing this?
Thanks!
Change your last two strings to:
Thread writeThread = new ConnectThread(targetdevice);
When you need to start your ConnectThread use start() method:
writeThread.start(); //If you need start run() method of ConnectThread.
Related
I am new to Programming with Java, and I am trying to send some value from 'Blueterm' application on Android and receive it on my Raspberry pi 3 via Bluetooth. Already raspberrypi3 has built in bluetooth and I am able to pair the 2 devices but I am not able to connect them and don't know how to start with the Java code. I hava tried ConnectedThread and AcceptThread but no progress, so if anyone could help me with this.
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.UUID;
import javax.bluetooth.*;
import android.bluetooth.*;
public class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
private UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public AcceptThread() {
BluetoothAdapter Badp= BluetoothAdapter.getDefaultAdapter();
if (Badp == null) {
// Device does not support Bluetooth
System.out.println("Bluetooth Not Supported");
}
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = Badp.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) { }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
manageConnectedSocket(socket);
try {
mmServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
private void manageConnectedSocket(BluetoothSocket socket) {
//acceptThread.cancel();
}
}
I'm just analyzing one of android sample applications - the bluetooth chat: https://developer.android.com/samples/BluetoothChat/project.html . I'm looking at the BluetoothChatService class ( https://developer.android.com/samples/BluetoothChat/src/com.example.android.bluetoothchat/BluetoothChatService.html ), at the constructor of its inner class called ConnectThread. There is such piece of code there:
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
(...)
public ConnectThread(BluetoothDevice device, boolean secure) {
(...)
BluetoothSocket tmp = null;
(...)
try {
if (secure) {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} else {
tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
}
mmSocket = tmp;
}
(...)
I don't understand - why they first assign the object to the tmp value and then copy it to mmSocket attribute? They could do it a bit simpler, this way:
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
(...)
public ConnectThread(BluetoothDevice device, boolean secure) {
(...)
try {
if (secure) {
mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} else {
mmSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
}
}
Shortly, because mmSocket is marked as final variable.
Let's see that your version of code. If method createRfcommSocketToServiceRecord or method createInsecureRfcommSocketToServiceRecord throws exception, the variable is not initialized. So the temporary variable makes sure that there is atleast null to be assigned to mmSocket.
That's the reason.
I have modified the android app "Bluetooth Chat" that you can find in android sdk examples version 2.1
The app estabilished a bluetooth connection with arduino, and, when with the app I send 0 or 1, arduino send a simple message "You have pressed 0 or 1".
It works if I test with eclipse's debug, but when I test with my smartphone, the result in the display is different, arduino's string is fragmented
example: smartphone: 0 -> arduino "You have pressed 0 or 1"
smartphone display: "y"
"ou pr"
The rest of the string was lost or not shown in the display.
Can you help me?
No error in logcat, only this bug.
This is the code:
public class BluetoothLampService {
// Debugging
private static final String TAG = "BluetoothLampService";
private static final boolean D = true;
// Name for the SDP record when creating server socket
private static final String NAME = "BluetoothLamp";
// Unique UUID for this application - Standard SerialPortService ID
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Member fields
private final BluetoothAdapter Adapter;
private final Handler Handler;
// private AcceptThread AcceptThread;
private ConnectThread ConnectThread;
private ConnectedThread ConnectedThread;
private int State;
// Constants that indicate the current connection state
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
/**
* Constructor. Prepares a new BluetoothChat session.
* #param context The UI Activity Context
* #param handler A Handler to messages back to the UI Activity
*/
public BluetoothLampService(Context context, Handler handler) {
Adapter = BluetoothAdapter.getDefaultAdapter();
State = STATE_NONE;
Handler = handler;
}
/**
* Set the current state of the chat connection
* #param state An integer defining the current connection state
*/
private synchronized void setState(int state) {
State = state;
// Give the new state to the Handler so the UI Activity can update
Handler.obtainMessage(MainActivity.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
}
/**
* Return the current connection state. */
public synchronized int getState() {
return State;
}
/**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume() */
public synchronized void start() {
// Cancel any thread attempting to make a connection
if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;}
// Cancel any thread currently running a connection
if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;}
// Start the thread to listen on a BluetoothServerSocket
// if (AcceptThread == null) {
// AcceptThread = new AcceptThread();
// AcceptThread.start();
// }
setState(STATE_LISTEN);
}
/**
* Start the ConnectThread to initiate a connection to a remote device.
* #param device The BluetoothDevice to connect
*/
public synchronized void connect(BluetoothDevice device) {
// Cancel any thread attempting to make a connection
if (State == STATE_CONNECTING) {
if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;}
}
// Cancel any thread currently running a connection
if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;}
// Start the thread to connect with the given device
ConnectThread = new ConnectThread(device);
ConnectThread.start();
setState(STATE_CONNECTING);
}
/**
* 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) {
// Cancel the thread that completed the connection
if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;}
// Cancel any thread currently running a connection
if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;}
// Cancel the accept thread because we only want to connect to one device
// if (AcceptThread != null) {AcceptThread.cancel(); AcceptThread = null;}
// Start the thread to manage the connection and perform transmissions
ConnectedThread = new ConnectedThread(socket);
ConnectedThread.start();
// Send the name of the connected device back to the UI Activity
Message msg = Handler.obtainMessage(MainActivity.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.DEVICE_NAME, device.getName());
msg.setData(bundle);
Handler.sendMessage(msg);
setState(STATE_CONNECTED);
}
/**
* Stop all threads
*/
public synchronized void stop() {
if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;}
if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;}
// if (AcceptThread != null) {AcceptThread.cancel(); AcceptThread = null;}
setState(STATE_NONE);
}
/**
* Write to the ConnectedThread in an unsynchronized manner
* #param out The bytes to write
* #see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (State != STATE_CONNECTED) return;
r = ConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
/**
* Indicate that the connection attempt failed and notify the UI Activity.
*/
private void connectionFailed() {
setState(STATE_LISTEN);
// Send a failure message back to the Activity
Message msg = Handler.obtainMessage(MainActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.TOAST, "Unable to connect device");
msg.setData(bundle);
Handler.sendMessage(msg);
}
/**
* Indicate that the connection was lost and notify the UI Activity.
*/
private void connectionLost() {
setState(STATE_LISTEN);
// Send a failure message back to the Activity
Message msg = Handler.obtainMessage(MainActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.TOAST, "Device connection was lost");
msg.setData(bundle);
Handler.sendMessage(msg);
}
/**
* This thread runs while listening for incoming connections. It behaves
* like a server-side client. It runs until a connection is accepted
* (or until cancelled).
*/
/*
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket ServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try {
tmp = Adapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
}
ServerSocket = tmp;
}
public void run() {
//Looper.prepare();
setName("AcceptThread");
BluetoothSocket socket = null;
// Listen to the server socket if we're not connected
while (State != STATE_CONNECTED) {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket = ServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
synchronized (BluetoothLampService.this) {
switch (State) {
case STATE_LISTEN:
case STATE_CONNECTING:
// Situation normal. Start the connected thread.
connected(socket, socket.getRemoteDevice());
break;
case STATE_NONE:
case STATE_CONNECTED:
// Either not ready or already connected. Terminate new socket.
try {
socket.close();
} catch (IOException e) {
}
break;
}
}
}
}
// Looper.loop();
}
public void cancel() {
try {
ServerSocket.close();
} catch (IOException e) {
}
}
}
*/
/**
* This thread runs while attempting to make an outgoing connection
* with a device. It runs straight through; the connection either
* succeeds or fails.
*/
private class ConnectThread extends Thread {
private final BluetoothSocket Socket;
private final BluetoothDevice Device;
public ConnectThread(BluetoothDevice device) {
Device = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
}
Socket = tmp;
}
public void run() {
Looper.prepare();
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
Adapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
Socket.connect();
} catch (IOException e) {
connectionFailed();
// Close the socket
try {
Socket.close();
} catch (IOException e2) {}
// Start the service over to restart listening mode
BluetoothLampService.this.start();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothLampService.this) {
ConnectThread = null;
}
// Start the connected thread
connected(Socket, Device);
Looper.loop();
}
public void cancel() {
try {
Socket.close();
} catch (IOException e) {
}
}
}
/**
* This thread runs during a connection with a remote device.
* It handles all incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket Socket;
private final InputStream InStream;
private final OutputStream OutStream;
public ConnectedThread(BluetoothSocket socket) {
Socket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
InStream = tmpIn;
OutStream = tmpOut;
}
public void run() {
Looper.prepare();
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
// FUNZIONANTE
bytes = InStream.read(buffer);
Log.i("BYTES", Integer.toString(bytes));
//String dati = new String(buffer);
//fine aggiunto da me
// Send the obtained bytes to the UI Activity
Handler.obtainMessage(MainActivity.MESSAGE_READ, 27, -1, buffer).sendToTarget();//buffer
} catch (IOException e) {
connectionLost();
break;
}
}
Looper.loop();
}
/**
* Write to the connected OutStream.
* #param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
OutStream.write(buffer);
// Share the sent message back to the UI Activity
Handler.obtainMessage(MainActivity.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
} catch (IOException e) {
}
}
public void cancel() {
try {
Socket.close();
} catch (IOException e) {
}
}
}
}
Have you already gived permission to your android app on your Manifest file?
uses-permission android:name="android.permission.BLUETOOTH" /
uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /
Then check the serial baude rate on your arduino serial connection too.
Kindly try by first pairing the device explicitly from your Android phone's settings. Usually the pair code is 1234
I have a sample application which transfers 30 char length data through Bluetooth.Data transfer was proper for four days,and then disconnected.Then after,when ever connection is established after few minutes Bluetooth connection is lost.adding adb logs and code.
Why i am getting disconnect from platform due to device property change ? when will the device property change ? is the device property change is the reason to loose Bluetooth connection?
private static final UUID MY_UUID_SECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private String mSocketType;
public ConnectThread(BluetoothDevice device, boolean secure) {
mmDevice = device;
BluetoothSocket tmp = null;
mSocketType = secure ? "Secure" : "Insecure";
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
}
mmSocket = tmp;
Log.i("12345", "Socket set");
}
public void run() {
Log.i("12345", "BEGIN mConnectThread SocketType:" + mSocketType);
setName("ConnectThread" + mSocketType);
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
Log.i(TAG, "Closing Socket 3");
} catch (IOException e2) {
Log.e(TAG, "unable to close() " + mSocketType + " socket during connection failure", e2);
}
connectionFailed();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothChatService.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice, mSocketType);
}
Logs :
09-12 11:16:36.230 V/BluetoothEventLoop.cpp( 2255): event_filter: Received signal org.bluez.Device:PropertyChanged from /org/bluez/3179/hci0/dev_22_89_8E_A9_50_1C
09-12 11:16:36.230 D/BluetoothEventLoop( 2255): Device property changed
09-12 11:16:36.240 D/BluetoothA2DPStateReceiver(20246): BluetoothA2DPStateReceiver constructor call()
09-12 11:16:36.245 D/BluetoothA2DPStateReceiver(20246): onReceive(): action = android.bluetooth.device.action.ACL_DISCONNECTED
09-12 11:16:36.245 D/BluetoothA2DPStateReceiver(20246): ACTION_ACL_DISCONNECTED
09-12 11:16:36.245 D/BluetoothA2DPSinkInfo(20246): checkBlackListCarkit() : isBlackListCarkit false
09-12 11:16:36.660 D/KeyguardViewMediator( 2255): setHidden false
May be due to the link loss, BT adapter had initiated the property changed command to report link disconnected to the upper layers. Please check in multitple devices.
Ok, so I am little perplexed as to why synchronized was used in the line marked below.
To me, you only use synchronized where a block of code will potentially be accessed by multiple threads however this code is only ever called from this thread in its run method.
An instance of mConnectThread is declared as a field at the very start of the class.
public class BluetoothChatService {
// Member fields
private ConnectThread mConnectThread;
Any ideas?
/**
* This thread runs while attempting to make an outgoing connection
* with a device. It runs straight through; the connection either
* succeeds or fails.
*/
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private String mSocketType;
public ConnectThread(BluetoothDevice device, boolean secure) {
mmDevice = device;
BluetoothSocket tmp = null;
mSocketType = secure ? "Secure" : "Insecure";
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
if (secure) {
tmp = device.createRfcommSocketToServiceRecord(
MY_UUID_SECURE);
} else {
tmp = device.createInsecureRfcommSocketToServiceRecord(
MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
}
mmSocket = tmp;
}
public void run() {
Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
setName("ConnectThread" + mSocketType);
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() " + mSocketType +
" socket during connection failure", e2);
}
connectionFailed();
return;
}
/********* THIS BIT OF CODE BELOW IS WHAT I AM ASKING ABOUT **********/
// Reset the ConnectThread because we're done
synchronized (BluetoothChatService.this) {
mConnectThread = null;
}
/**********************************^^*********************************/
// Start the connected thread
connected(mmSocket, mmDevice, mSocketType);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e);
}
}
}
Cheers
You can have multiple ConnectThread objects going simultaneously, which means multiple threads in the same run method(technically, copies of the run method, but the same code), though they'll all have access to different member variables. The synchronized block is syncing on an external object, so I suspect there's a synchronized block somewhere else in the program that looks like
synchronized (BluetoothChatService.this)
{
if (mConnectThread != null)
do some work that would throw NPE without the check.
}
Edit:
To clarify, they aren't preventing two threads from accessing the same block of code, they're preventing two threads from accessing the same variable from different sections of code.