Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 204402

Recieving Data over Bluetooth

$
0
0

So, I have a bluetooth barcode reader to send barcode data to my Android Tablet. The data should be displayed in an EditText. So I wrote the following code:

//mac address is known so I skipped the first phases foreach (BluetoothDevice device in pairedDevices) { if (device.Address == mac) { UUID uuid = UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"); BluetoothSocket mySocket = device.CreateRfcommSocketToServiceRecord (uuid); Thread thread = new Thread(() => BTConnect(mySocket)); thread.Start(); } } void BTConnect(BluetoothSocket mySocket) { try { mySocket.Connect (); myStream = soket.InputStream; thread = new Thread(() => BTRead(mySocket)); thread.Start(); return; } catch { mySocket.Close(); RunOnUiThread (() => AlertD ("ConnProblem")); return; } } public void BTRead() { byte[] buffer = new byte[1024]; // buffer store for the stream int bytes; // bytes returned from read() while (true) { try { bytes = myStream.Read(buffer, 0, buffer.Length); byte[] readBuf = (byte[]) buffer; var readMessage = new Java.Lang.String (readBuf, 0, bytes); if(readMessage != null) { RunOnUiThread (() => barcode.Text = ""); //clear the edittext RunOnUiThread (() => barcode.Append (readMessage)); //append the data } } catch { RunOnUiThread (() => AlertD ("ConnProblem")); } } }

Well, this code...kinda worked at first. But as I tested it again and again, it started to behave unexpectedly. Sometimes nothing happens at all (EditText does not change). Sometimes ConnProblem error is catched for no apparent reason. Sometimes the app crashes. But occasionally, it runs as I want it to be.

Now the thing is, this action is not exclusive for an Activity, it MUST always run behind. For this, I assigned the "BluetoothSocket mySocket" into a static varible and copied the "BTRead" function in all activities. Which seems like a dumb solution in the first place.

Second thing is about this "RunOnUiThread" function. It feels really unstable and I look for a solution without using it at all (maybe use them only for alertdialogs).

I just want to read the data, so it's a one-way action. I'm aware of the BluetoothChat example. But it's just too broad and confusing. I guess I should use handlers for such an action, but I don't have the slightest idea on how to use them (always used "Events" as Xamarin encouraged). Can someone please help?


Viewing all articles
Browse latest Browse all 204402

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>