Bluetooth programming in C - android

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) { }
}
}
}

Related

Connected Thread return null object

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

Android Bluetooth RFCOMM can't receive strings

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) { }
}
}
}

Bluetooth connection doesn't close

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;
}
}
};

Not able to read any data from Bluetooth device in Android

I am having a bluetooth device . Basically i want my app to connect to the device and receive the data it sends.However so far i am able to connect to the bluetooth device,but i am not able to receive any inputs from it .
here is my problem:
i) DataInputStream.available() always return 0.
ii) If i use any breakpoint on line
bytes = input.read(buffer); // This will freeze doesn't show anything.
and line below it never executes
public class ConnectThread extends Thread{
final String TAG="ConnectThread";
private ReadThread mReadThread = null;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private boolean isDeviceConnected;
public final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothSocket mmSocket = null;
Handler mHandler;
BluetoothDevice bTdevice;
private DataInputStream mReadData = null;
public ConnectThread(BluetoothDevice bTdevice, Handler mHandler) {
super();
this.bTdevice = bTdevice;
this.mHandler = mHandler;
InputStream tmpIn = null;
OutputStream tmpOut = null;
BluetoothSocket socket;
try {
socket = bTdevice.createRfcommSocketToServiceRecord(MY_UUID);
System.out.println("**** Socket created using standard way******");
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
mmSocket = socket;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
#Override
public synchronized void run() {
// TODO Auto-generated method stub
super.run();
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter != null) {
adapter.cancelDiscovery();
Log.i("***Bluetooth Adapter**", "Bluetooth Discovery Canceled");
}
if (mmSocket != null) {
mmSocket.connect();
Log.i("***Socket Connection Successful**", "Socket Connection Successful");
isDeviceConnected = true;
mReadData = new DataInputStream(mmSocket.getInputStream());
Log.i("***Read data**", "" + mReadData);
if (mReadThread == null) {
mReadThread=new ReadThread(mReadData,mmSocket);
mReadThread.start();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("***Error**", "Socket Connection failed");
e.printStackTrace();
try {
mmSocket.close();
isDeviceConnected = false;
} catch (IOException closeException) {
e.printStackTrace();
}
}
// mHandler.obtainMessage(DisplayBtdataActivity.SUCCESS_CONNECT,mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
// Read the data from device
private class ReadThread extends Thread {
/** The input. */
private DataInputStream input;
/**
* Constructor for ReadThread.
*
* #param input
* DataInputStream
*/
private BluetoothSocket mSocket;
public ReadThread(DataInputStream input, BluetoothSocket socket) {
this.input = input;
this.mSocket = socket;
}
/**
* Method run.
*
* #see java.lang.Runnable#run()
*/
public synchronized void run() {
try {
Log.d(TAG, "ReadThread run");
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
bytes = input.available(); // always return 0
// bytes = mReadData.readInt();
Log.i("***Bytes data**", "" + bytes);// print 0
Log.i("***Data input stream**", "" + input); // Here input is not null
if (input != null) {
Log.i("***hello world**", "...");
while (isDeviceConnected) {
try {
bytes = input.read(buffer); // this code never executes
Log.i("**bytes data**", " " + bytes);
if (input != null) {
int len = input.readInt();
Log.i(TAG, "Response Length: " + len);
if (len > 65452) {// Short.MAX_VALUE*2
Log.i(TAG, "Error: Accesory and app are not in sync.");
continue;
}
Log.d(TAG, "Response Length: " + len);
Log.d(TAG, "Reading start time:" + System.currentTimeMillis());
byte[] buf = new byte[len];
Log.d(
TAG, "input.available() " + input.available());
if (input.available() > 0) {
input.readFully(buf);
System.out.println("Output:=");
}
Log.d(TAG, "Reading end time:" + System.currentTimeMillis());
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
isDeviceConnected = false;
}
}
}
} catch (Exception e) {
e.printStackTrace();
isDeviceConnected = false;
Log.e(TAG, "catch block 3 " + e.toString());
}
}
}
}
In ReadThread.Run() - you have to move the code
bytes = input.available (); // Always return 0
into while loop
1, you use input before checking for null if (input! = null)
2, Data is sent continuously and is a high probability that when running thread do not come any data, so therefore you have to give input.available bytes = (); into a while loop.
3, You can try to modify data processing. In principle, quickly read the data in the temporary buffer, and then move to MainBuffer and then manipulated with it. An example is in c # .net Xamarin, but just for an example :
private const int BTLPacketSize = 1024;
private const int BTLdataSize = 65536;
private System.Object InternaldataReadLock = new System.Object();
private System.Object dataReadLock = new System.Object();
private byte[] InternaldataRead = new byte[BTLPacketSize];//posila 64Byte pakety (resp. 62, protoze 2 jsou status bytes)
private byte[] TempdataRead = new byte[BTLPacketSize];
private byte[] dataRead = new byte[BTLdataSize];//Tyto pameti pouzivaji cursorc -> musim ohlidat preteceni pameti//Max. prenos rychlost je 115200 b/s.
private bool continueRead = true;
public override void Run()
{
while (continueRead)
{
try
{
int readBytes = 0;
lock (InternaldataReadLock)
{//Quick reads data into bigger InternaldataRead buffer and next move only "received bytes" readBytes into TempdataRead buffer
readBytes = clientSocketInStream.Read(InternaldataRead, 0, InternaldataRead.Length);
Array.Copy(InternaldataRead, TempdataRead, readBytes);
}
if (readBytes > 0)
{//If something reads move it from TempdataRead into main dataRead buffer a send it into MainThread for processing.
lock (dataReadLock)
{
dataRead = new byte[readBytes];
for (int i = 0; i < readBytes; i++)
{
dataRead[i] = TempdataRead[i];
}
}
Bundle dataBundle = new Bundle();
dataBundle.PutByteArray("Data", dataRead);
Message message = btlManager.sourceHandler.ObtainMessage();
message.What = 1;
message.Data = dataBundle;
btlManager.sourceHandler.SendMessage(message);
}
}
catch (System.Exception e)
{
if (e is Java.IO.IOException)
{
//.....
}
}
}
}

Sending received message back to UI activity, but app stuck

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();
}
}
}

Categories

Resources