i'm trying to exchange Strings between two android devices. I'm able to establishe a RFCOMM connection and sending a String. But my APP cant receive it. After days of trail and error and searching on the internet i hope somebody can help me:
Thats my code so far:
public class MainActivity extends AppCompatActivity {
BluetoothAdapter bluetoothAdapter;
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
Log.i("MAC", "in handler");
super.handleMessage(msg);
switch(msg.what){
case SUCCESS_CONNECT:
// DO something
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
connectedThread.run();
Toast.makeText(getApplicationContext(), "CONNECT", Toast.LENGTH_LONG).show();
String s = "successfully connected";
connectedThread.write(s.getBytes());
Log.i("MAC", "connected");
break;
case MESSAGE_READ:
byte[] readBuf = (byte[])msg.obj;
String string = new String(readBuf);
Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG).show();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
registerReceiver(mReceiver,filter);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)){
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i("MAC","Connect to : " +device.getAddress());
ConnectingThread ct = new ConnectingThread(device);
ct.start();
}
}
};
private class ConnectingThread extends Thread {
private final BluetoothSocket bluetoothSocket;
private final BluetoothDevice bluetoothDevice;
public ConnectingThread(BluetoothDevice device) {
BluetoothSocket temp = null;
bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
temp = bluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket = temp;
}
public void run() {
// Cancel any discovery as it will slow down the connection
bluetoothAdapter.cancelDiscovery();
try {
// This will block until it succeeds in connecting to the device
// through the bluetoothSocket or throws an exception
bluetoothSocket.connect();
} catch (IOException connectException) {
connectException.printStackTrace();
try {
bluetoothSocket.close();
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
// Code to manage the connection in a separate thread
mHandler.obtainMessage(SUCCESS_CONNECT, bluetoothSocket).sendToTarget();
/*
manageBluetoothConnection(bluetoothSocket);
*/
}
// Cancel an open connection and terminate the thread
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
Related
I am using bluetoothconnection service on my fragment but ConnectedThread return empty. Although i am calling bluetoothconnection service but doesnt work. I dont find any solutions for this. How can i fix ?
Fragment:
if(convertView==null) {
convertView = inflater.inflate(R.layout.fragment_ota__update, container, false);
text=(TextView)convertView.findViewById(R.id.text);
InputStream is =this.getResources().openRawResource(R.raw.blink);
BufferedReader reader = new BufferedReader( new InputStreamReader(is));
send =(Button) convertView.findViewById(R.id.send);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
getActivity().registerReceiver(mBroadcastReceiver4, filter);
mBluetoothConnection = new BluetoothConnectionService(getActivity().getApplicationContext());
mBluetoothConnection.startClient(mBTDevice,MY_UUID_INSECURE);
if(is!=null){
try {
while ((data = reader.readLine()) != null) {
char [] ch =data.toCharArray();
for (char c: ch) {
int i= (int) c;
sbuffer.append(Integer.toHexString(i).toUpperCase());
text.setText(sbuffer);
}
}
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sbuffer!=null) {
byte[] bytes = sbuffer.toString().getBytes(Charset.defaultCharset());
mBluetoothConnection.write(bytes);
}
}
});
}
In the fragment i am calling with this code:
mBluetoothConnection = new BluetoothConnectionService(getActivity().getApplicationContext());
BluetoothConnectionService part of write function
public void write(byte[] out) {
if(mConnectedThread !=null ){
// Create temporary object
// Synchronize a copy of the ConnectedThread
Log.d(TAG, "write: Write Called.");
//perform the write
mConnectedThread.write(out);
}
else{
Log.d(TAG, "mConnectedThread empty ");
}
}
And this is my bluetooth connection class :https://paste.ubuntu.com/p/gcPrydZnDw/
Your code is not something I can fix directly. But I here is aan example of how I made a connection and then send data to this connected device:
public class BluetoothConnection extends Thread {
public static BluetoothSocket mSocket;
private InputStream mInStream;
private OutputStream mOutStream;
private byte[] buffer;
private BluetoothAdapter mAdapter;
private Handler mHandler;
private String output;
private String sendString;
private String tempTester = "";
static UUID MY_UUID;
/**
* Constructor initializes all necessary variables.
* #param device the device that the constructor will connect to
*/
public BluetoothConnection(BluetoothDevice device){
MY_UUID = device.getUuids()[0].getUuid();
mAdapter = null;
mSocket = createMSocket(device);
mSocket = connectSocket(mSocket);
InputStream tmpIn = null;
OutputStream tmpOut = null;
try{
tmpIn = mSocket.getInputStream();
tmpOut = mSocket.getOutputStream();
}catch (IOException e){
e.printStackTrace();
}
mInStream = tmpIn;
mOutStream = tmpOut;
buffer = new byte[25];
}// end constructor
/**
* Creates the main socket that will be used in connection with device.
* #param device a BluetoothDevice
* #return a BluetoothSocket mSocket.
*/
private BluetoothSocket createMSocket(BluetoothDevice device) {
BluetoothSocket tmp = null;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
return tmp;
}// end createMSocket
/**
* Socket makes connection to device then returns back the updated socket.
* #param socket BluetoothSocket
* #return an updated version of the parameter socket.
*/
private BluetoothSocket connectSocket(BluetoothSocket socket){
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket.connect();
System.out.println("$$$$$$$$$$$$$$$$****** socket connected ******$$$$$$$$$$$$$$$$");
} catch (IOException e) {
//connection to device failed so close the socket
try {
socket.close();
System.out.println("$$$$$$$$$$$$$$$$****** socket closed ******$$$$$$$$$$$$$$$$");
} catch (IOException e2) {
e2.printStackTrace();
}
}
return socket;
}// end connectSocket
/**
* Sends message back to device in the form of a byte[].
* #param buffer byte[]
*/
public void write(byte[] buffer){
try{
mOutStream.write(buffer);
}catch(IOException e) {
e.printStackTrace();
}
}// end write
/**
* Closes the connection with the device
*/
public void cancel(){
try{
mSocket.close();
}catch(IOException e){
e.printStackTrace();
}
}// end cancel
}
Then on your main thread in an activity, you can call the following code (as long as you know the device you are connecting to):
BluetoothConnection connection = new BluetoothConnection(connectedDevice);
public void sendData(){
String s = editText.getText().toString();
byte[] b = s.getBytes();
connection.write(b);
//System.out.println("Bytes Sent");
}// end sendData
hello everybody i have been working on this app for so long now, and i think i almost finished but there is a problem and i tried a lot of different ways to solve it but i couldn't so any help i would appreciate .
the app is simple Bluetooth data sender to an Bluetooth module and it works just fine the problem occur if i wanted to close the connection from the app i couldn't close it and i have tried interrupt and the cancel method and putting a condition in a while loop but without any luck so can anyone help me please thank you.
this is my client thread (the same as android developer)
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private boolean x;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Log.i(tag, "construct");
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
}
catch (IOException e) {
// Log.i(tag, "get socket failed");
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
while (true) {
bluetoothAdapter.cancelDiscovery();
Log.i(tag, "connect - run");
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
Log.i(tag, "connect - succeeded");
} catch (IOException connectException) {
Log.i(tag, "connect failed");
// 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)
xHandler.obtainMessage(0, mmSocket).sendToTarget();
if(x==false){
break;
}
}
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
Log.i(tag,"cancel 1");
mmSocket.close();
x=false;
// mmDevice.close();
} catch (IOException e) { }
}
}
and this is my connected class
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private boolean x;
//private FileInputStream fis;
private int s;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
//s=x;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
// if (s == 1) {
byte[] buffer;
// buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs}
//}
while (x) {
try {
// Read from the InputStream
buffer=new byte[1024];
// buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
xHandler.obtainMessage(1, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
Log.i(tag,"write");
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
mmInStream.close();
mmOutStream.close();
x=false;
Log.i(tag,"cancel 2");
}
catch (IOException e) { }
}
}
and finally the handler:
public Handler xHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
Log.i(tag, "in handleeer");
super.handleMessage(msg);
switch(msg.what){
case 0:
// DO something
// if(omar==1){
//(BluetoothSocket)msg.obj
// bluetoothSocket=(BluetoothSocket).msg.obj;
connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(), "CONNECT", Toast.LENGTH_LONG).show();
//omar++;}
//String s = "79";
String s="h";
connectedThread.write(s.getBytes());
Log.i(tag, "connected");
break;
case 1:
byte[] readBuf = (byte[])msg.obj;
String string = new String(readBuf);
Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG).show();
break;
}
}
};
I managed to successfully connect two android phones using apps i made and I tried to use what I learned there to connect an android phone to my raspberry pi( which uses Raspbian Jessie ). I tried to implement the server side on the raspberry and use the client version of my android app. But i noticed something was missing in the code this gentleman wrote: http://people.csail.mit.edu/albert/bluez-intro/x502.html
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
int main(int argc, char **argv)
{
struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
char buf[1024] = { 0 };
int s, client, bytes_read;
socklen_t opt = sizeof(rem_addr);
// allocate socket
s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
// bind socket to port 1 of the first available
// local bluetooth adapter
loc_addr.rc_family = AF_BLUETOOTH;
loc_addr.rc_bdaddr = *BDADDR_ANY;
loc_addr.rc_channel = (uint8_t) 1;
bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr));
// put socket into listening mode
listen(s, 1);
// accept one connection
client = accept(s, (struct sockaddr *)&rem_addr, &opt);
ba2str( &rem_addr.rc_bdaddr, buf );
fprintf(stderr, "accepted connection from %s\n", buf);
memset(buf, 0, sizeof(buf));
// read data from the client
bytes_read = read(client, buf, sizeof(buf));
if( bytes_read > 0 ) {
printf("received [%s]\n", buf);
}
// close connection
close(client);
close(s);
return 0;
}
In android I had to hard code a UUID into both the server and the client side but here I see no reference to anything that might be a UUID. Why is that?
This is the android code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
System.exit(1);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
Object[] pairedDev = pairedDevices.toArray();
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, 0);
/*if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
ListView listView = (ListView) findViewById(R.id.PairedDevicesListView);
listView.setAdapter(mArrayAdapter);*/
ConnectThread connectThread = new ConnectThread((BluetoothDevice) pairedDev[1]);
connectThread.run();
connectThread.cancel();
}
public void buttonOnClick(View v)
{
Button button = (Button) v;
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onRestart() {
super.onRestart();
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
try {
tmp = device.createRfcommSocketToServiceRecord(UUID.fromString("F4C20AC0-3DF8-11E6-BDF4-0800200C9A66"));
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
mmSocket.close();
System.exit(1);
} catch (IOException closeException) { System.exit(1); }
return;
}
// Do work to manage the connection (in a separate thread)
// manageConnectedSocket(mmSocket);
byte[] bytes = new byte[3];
bytes[0] = 1;
bytes[1] = 3;
bytes[2] = 2;
ConnectedThread connectedThread = new ConnectedThread(mmSocket);
connectedThread.write(bytes);
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
// mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
static class BluetoothInHandler extends Handler {
private final WeakReference<Bluetooth_dataDisplay> mActivity;
BluetoothInHandler(Bluetooth_dataDisplay activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
final Bluetooth_dataDisplay thizz = mActivity.get();
if (thizz == null) return;
if (msg.what == thizz.handlerState) {
String readMessage = (String) msg.obj;
thizz.myLabel.setText(readMessage);
}
}//end of handle message
}//end of Bluetoothin handler
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth_datadisplay);
myLabel = (TextView)findViewById(R.id.label);
mMyHandler = new BluetoothInHandler(this);
}//end oncreate
#Override
public void onResume() {
super.onResume();
String MAC = getIntent().getStringExtra("MAC");
mAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice bluetoothDevice = mAdapter.getRemoteDevice(MAC);
ConnectingThread t = new ConnectingThread(bluetoothDevice);
t.start();
}
//Setting Up a Connecting Client
private class ConnectingThread extends Thread {
OutputStream mmOutputStream;
InputStream mmInputStream;
StringBuilder recDataString = new StringBuilder();
// private final BluetoothSocket bluetoothSocket;
private final BluetoothDevice bluetoothDevice;
final Handler handler = new Handler();
public ConnectingThread(BluetoothDevice device) {
BluetoothSocket temp = null;
bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket = temp;
}
public void run() {
// Cancel any discovery as it will slow down the connection
mAdapter.cancelDiscovery();
try {
// This will block until it succeeds in connecting to the device
// through the bluetoothSocket or throws an exception
bluetoothSocket.connect();
Log.e("bluetooth socket",".connect");
mmOutputStream = bluetoothSocket.getOutputStream();
mmInputStream = bluetoothSocket.getInputStream();
//beginListenForData();
Bluetooth_dataDisplay.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(Bluetooth_dataDisplay.this, "Connected with Device!", Toast.LENGTH_SHORT).show();
}
});
handler.post(new Runnable() {
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInputStream.read(buffer);
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
mMyHandler.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
});
//beginListenForData();
//Log.e("begin", "begindata");
} catch (IOException connectException) {
connectException.printStackTrace();
try {
bluetoothSocket.close();
Log.e("click6", "blueclose");
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
}
Trying to send data from thread back to UI activity but my app just stuck. :( I don't know what wrong with it. Please help. No error and no crashes of app. I had tried runnableUIthread as well. It didn't work too. So I don't know what to do now.
static class BluetoothInHandler extends Handler {
private final WeakReference<Bluetooth_dataDisplay> mActivity;
BluetoothInHandler(Bluetooth_dataDisplay activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
//change 3
Log.e("test","handleMessage");
final Bluetooth_dataDisplay thizz = mActivity.get();
if (thizz == null) return;
if (msg.what == thizz.handlerState) {
String readMessage = (String) msg.obj;
thizz.myLabel.setText(readMessage);
}
}//end of handle message
}//end of Bluetoothin handler
#Override
public void onResume() {
super.onResume();
String MAC = getIntent().getStringExtra("MAC");
mAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice bluetoothDevice = mAdapter.getRemoteDevice(MAC);
ConnectingThread t = new ConnectingThread(bluetoothDevice,mMyHandler );
t.start();
}
//Setting Up a Connecting Client
private class ConnectingThread extends Thread {
OutputStream mmOutputStream;
InputStream mmInputStream;
StringBuilder recDataString = new StringBuilder();
// private final BluetoothSocket bluetoothSocket;
private final BluetoothDevice bluetoothDevice;
Handler handler;
public ConnectingThread(BluetoothDevice device,Handler mHandler) {
handler = mHandler
BluetoothSocket temp = null;
bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket = temp;
}
public void run() {
// Cancel any discovery as it will slow down the connection
mAdapter.cancelDiscovery();
try {
// This will block until it succeeds in connecting to the device
// through the bluetoothSocket or throws an exception
bluetoothSocket.connect();
Log.e("bluetooth socket",".connect");
mmOutputStream = bluetoothSocket.getOutputStream();
mmInputStream = bluetoothSocket.getInputStream();
//beginListenForData();
Bluetooth_dataDisplay.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(Bluetooth_dataDisplay.this, "Connected with Device!", Toast.LENGTH_SHORT).show();
}
});
//change 7
//handler.post(
new Runnable() {
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// Keep looping to listen for received messages
while (true) {
//change 1
try{
Thread.sleep(1000);
}catch(Throwable e){
e.printStackTrace();
}
try {
bytes = mmInputStream.read(buffer);
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
//change 4;
handler.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
//change 6
Log.e("test","6")
//change 2
e.printStackTrace();
break;
}catch(Throwable e1){
//change 5;
Log.e("test","5")
}
}
}.run();
//});
//beginListenForData();
//Log.e("begin", "begindata");
} catch (IOException connectException) {
connectException.printStackTrace();
try {
bluetoothSocket.close();
Log.e("click6", "blueclose");
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
}
I am beginner in Android and I have a problem with receiving the data stream sent from Bluetooth by RfcommSocket and add it to LinkedHashMap ? I use the code below but it doesn't work and I don't know, how can I deal with it?
public class BluetoothConnectionThread extends Thread{
public static final int MESSAGE_READ = 9999;
private final BluetoothDevice btDevice;
private BluetoothSocket btSocket;
private InputStream inStream;
private OutputStream outStream;
Map<Integer, Byte[]> linkedHashMap = new LinkedHashMap<Integer, Byte[]>();
private static UUID uuid = UUID.fromString("ae3fdfc0-8bd1-11e5-8994-feff819cdc9f");
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
String address = null;
switch (msg.what) {
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
break;
}
}
};
public BluetoothConnectionThread(BluetoothDevice device) {
this.btDevice = device;
try
{
btSocket = this.btDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException ex) {
btSocket = null;
}
}
public void ConnectedThread(BluetoothSocket socket) {
this.btSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
inStream = tmpIn;
outStream = tmpOut;
}
public void run() {
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
byte[] buffer = new byte[32];
int bytes;
try {
btSocket.connect();
bytes = inStream.read(buffer);
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch(IOException ex) {
try {
btSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes) {
try {
outStream.write(bytes);
} catch (IOException e) { }
}
public void cancel() {
try {
btSocket.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
In answer to why it's not working, you are not adding any values to the hashmap.
Depending on how you are selecting the key Integer, I have just used a static int for demonstration purposes, but this isn't the best way to go about this. If this is how you are generating the key I would suggest a List.
static int intKey = 0;
In your case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
linkedHashMap .put(intKey, readBuf)
intKey++;
I suggest you examine other ways of doing this, or as you do not seem to have a clear idea of how or why you are using a linked hash map.