Issues receiving data through bluetooth in my Android application - java

For my robotics exam this summer, I am building a robot, that I want to communicate with an Android device via Bluetooth. For this purpose, I am writing my own Android application. I have no issues sending data, however i cannot receive data. My code for receiving the data, that doesn't work, looks like this:
new Thread(new Runnable() {
public void run(){
byte[] buffer = new byte[1024]; //Buffer for the incoming message
int bytes;
TextView afstandsTekst = (TextView)findViewById(R.id.afstandsText);
//Listen to the InputStream
while(true){
try {
if(mmInStream.available() != 0)
try {
bytes = mmInStream.read(buffer); //Read from the InputStream. This is where the app crashes.
}
catch(IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
break;
}
afstandsTekst.setText(String.valueOf(bytes));
}
}
}).start();
The app crashes at
bytes = mmInStream.read(buffer);
and I do not understand why. I've used the bluetooth page at Android Developers for help (http://developer.android.com/guide/topics/wireless/bluetooth.html#ManagingAConnection), and have tried doing it exactly as they did, but that still crashed, which is why I've now tried the code that I have pasted above.
Also, even though the app crashes when run normally, when I choose to debug it in Eclipse on my Samsung Galaxy Nexus, the application does not crash, and I do not know why.
This is my first post to this forum, and I very much hope that someone out there will have an answer. Thanks in advance!
Edit: Here's the code in its entirety:
package skole.migogjesper.hospitalsseng;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.bluetooth.BluetoothClass.Device;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class HospitalssengActivity extends Activity {
private String address = "00:06:66:45:B8:DB";
private static final int REQUEST_ENABLE_BT = 3;
protected static final String EXTRA_DEVICE_ADDRESS = null;
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
public ArrayAdapter<String> mArrayAdapter;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //Indlæser bluetooth modulet i enheden.
private BluetoothDevice mmDevice = mBluetoothAdapter.getRemoteDevice(address);
private OutputStream mmOutStream;
private InputStream mmInStream;
private char stueDestination = '0';
private char scannerDestination = '1';
private char operationsstueDestination = '2';
private char krematorieDestination = '3';
private char xrayDestination = '4';
private char planlagtStueDestination = 'q';
private char planlagtScannerDestination = 'w';
private char planlagtOperationsstueDestination = 'e';
private char planlagtKrematorieDestination = 'r';
private char planlagtXrayDestination = 't';
private byte sendByte;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if(mBluetoothAdapter == null){ //Tjekker om bluetooth er underst¯ttet.
Toast.makeText(HospitalssengActivity.this, "Enheden understøtter ikke bluetooth", Toast.LENGTH_LONG).show();
}
if(!mBluetoothAdapter.isEnabled()){ //Tjekker om bluetooth er tÊndt.
Intent enableBtIntent = new Intent (BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
new Thread(new Runnable() {
public void run(){
byte[] buffer = new byte[1024]; //Buffer til den indkommende besked
int bytes; //Bytes der kommer fra read()
TextView afstandsTekst = (TextView)findViewById(R.id.afstandsText);
//Lyt efter InputStream indtil der sker en exception
while(true){
try {
if(mmInStream.available() != 0)
try {
bytes = mmInStream.read(buffer); //Læs fra InputStream
}
catch(IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
break;
}
//afstandsTekst.setText(String.valueOf(bytes));
}
}
}).start();
}
private BluetoothSocket mmSocket;
public void Connect(BluetoothDevice device){
BluetoothSocket tmp = null; //Dette er er et midlertidigt objekt, som senere bliver assigned til mmSocket.
mmDevice = device;
try { //Få en BluetoothSocket, som kan bruges til at forbinde med en BluetoothDevice
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(device, 1);
} catch(Exception e) {
Toast.makeText(HospitalssengActivity.this, "FEJL!", Toast.LENGTH_LONG).show();
}
mmSocket = tmp;
try{ //Forbind enheden gennem socket'en. Dette blokerer indtil den er succesfuld eller den fejler.
mmSocket.connect();
} catch (IOException connectException) {
try{mmSocket.close();} //Fejlet forbindelse. Luk socket'en og hop ud af metoden.
catch(IOException closeException) {}
return;
}
}
public void cancel(){ //Lukker en forbindelse og lukker socket'en.
try{mmSocket.close();}
catch(IOException e) {}
}
public void write(byte sendByte){
try {
mmOutStream = mmSocket.getOutputStream();
mmOutStream.write(sendByte);
Toast.makeText(HospitalssengActivity.this, "Sendt", Toast.LENGTH_SHORT).show();
}
catch (IOException e) {}
}
public void scanKnap(View view){
Connect(mmDevice);
}
public void afbrydKnap(View view){
cancel();
}
public void stueKnap(View view){
CheckBox planlagtCheck = (CheckBox) findViewById(R.id.planlagtCheck);
if(!planlagtCheck.isChecked()){
sendByte = (byte) stueDestination;
write(sendByte);
}
if(planlagtCheck.isChecked()){
sendByte = (byte) planlagtStueDestination;
write(sendByte);
}
}
public void scannerKnap(View view){
CheckBox planlagtCheck = (CheckBox) findViewById(R.id.planlagtCheck);
if(!planlagtCheck.isChecked()){
sendByte = (byte) scannerDestination;
write(sendByte);
}
if(planlagtCheck.isChecked()){
sendByte = (byte) planlagtScannerDestination;
write(sendByte);
}
}
public void operationsstueKnap(View view){
CheckBox planlagtCheck = (CheckBox) findViewById(R.id.planlagtCheck);
if(!planlagtCheck.isChecked()){
sendByte = (byte) operationsstueDestination;
write(sendByte);
}
if(planlagtCheck.isChecked()){
sendByte = (byte) planlagtOperationsstueDestination;
write(sendByte);
}
}
public void krematorieKnap(View view){
CheckBox planlagtCheck = (CheckBox) findViewById(R.id.planlagtCheck);
if(!planlagtCheck.isChecked()){
sendByte = (byte) krematorieDestination;
write(sendByte);
}
if(planlagtCheck.isChecked()){
sendByte = (byte) planlagtKrematorieDestination;
write(sendByte);
}
}
public void xrayKnap(View view){
CheckBox planlagtCheck = (CheckBox) findViewById(R.id.planlagtCheck);
if(!planlagtCheck.isChecked()){
sendByte = (byte) xrayDestination;
write(sendByte);
}
if(planlagtCheck.isChecked()){
sendByte = (byte) planlagtXrayDestination;
write(sendByte);
}
}
}

You should not use threads.
Use Service for background stuff, and for threads use ASyncTask instead of Thread!
As a hint: You can broadcast locally between the Service and the activity! (You have to import android support library for that(see LocalBroadcast).
Android already means OS on top of another OS(Linux). You do not need to handle thread communication yourself, let Android take care of that!

If it runs in the debugger and not normally that sounds like a race condition. The only variable that seems to be available in more than one thread is mmInStream. What are you doing to mmInStream outside of this thread?
A race condition is when two threads can both access shared mutable state (in this case mmInStream). Sometimes one thread wins and you see one result and the other time another thread wins and you see another result. These things can be very difficult to debug.
Can you post the code around where you create the thread?
Looking at the code you posted I don't see where mmInstream is initialized. That would cause a null pointer exception like you reported, but it would also happen in the debugger (unless that thread never ran).

Related

Android Studio - Issue connecting with device resulting in the socket getting closed

I am attempting to create an android app that connects to an Bluetooth device and am struggling with connecting.When running the run() method when I try to connect it does not work and goes to the catch portion of the code giving me the output of "socket closed". i am not sure why the try is not working.
I am aware that my code has several flaws, i am on my 5th day of android developing, however any help I could get would be greatly appreciated. The big problem I need to fix is being able to connect to the device and ultimately being able to receive a stream of data from it.
public class BluetoothConnection extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
byte[] buffer;
BluetoothAdapter mmAdapter;
// Unique UUID for this application, you may use different
private static final UUID MY_UUID = UUID
.fromString("eb58f747-a241-4ccb-935d-04ac6039895d");
public BluetoothConnection(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmAdapter = null;
System.out.println("\n\n\n\n\n\n print is working? \n\n\n\n\n\n");
// Get a BluetoothSocket for a connection with the given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
mmSocket = tmp;
//now make the socket connection in separate thread to avoid FC
Thread connectionThread = new Thread(new Runnable() {
#Override
public void run() {
// Always cancel discovery because it will slow down a connection
Log.d("workkkkkk","$$$$$$$$$$$$$$$$****** printingggggg ******$$$$$$$$$$$$$$$$");
//mmAdapter.cancelDiscovery();
}
});
connectionThread.start();
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
System.out.println("\n\n\n\n\n\n socket connected\n\n\n\n\n\n");
} catch (IOException e) {
//connection to device failed so close the socket
try {
mmSocket.close();
System.out.println("\n\n\n\n\n\n socket closed\n\n\n\n\n\n");
} catch (IOException e2) {
System.out.println("\n\n\n\n\n\n in catch\n\n\n\n\n\n");
e2.printStackTrace();
}
}
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
buffer = new byte[1024];
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
// Keep listening to the InputStream while connected
while (true) {
try {
//read the data from socket stream
if(mmInStream != null) {
mmInStream.read(buffer);
}
// Send the obtained bytes to the UI Activity
} catch (IOException e) {
//an exception here marks connection loss
//send message to UI Activity
break;
}
}
}
public void write(byte[] buffer) {
try {
//write the data to socket stream
if(mmOutStream != null)
mmOutStream.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is being run in my DeviceList Class which is here. I am running into multiple problems here but the big one is pertaining to the BluetoothConnection.java however i am not sure if the issue is happening because of this class.
package com.example.curie.fairbanks_01;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.util.Log;
import android.view.View;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Switch;
import android.widget.Toast;
import android.content.Intent;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class DeviceList extends Activity {
Button deviceSearch;
Switch btSwitch;
private BluetoothAdapter BA;
private Set<BluetoothDevice>pairedDevices;
private String instrumentName;
private UUID instrumentUUID;
BluetoothSocket socket;
BluetoothConnection connector;
ListView lv;
public static BluetoothDevice instrument;
PopupMenu pMenu;
ArrayList<MenuItem> popupList;
ArrayList<BluetoothDevice> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
deviceSearch = (Button) findViewById(R.id.device_search);
deviceSearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PopupMenu popup = new PopupMenu(DeviceList.this, findViewById(R.id.device_search));
pairedDevices = BA.getBondedDevices();
list = new ArrayList<BluetoothDevice>();
for (BluetoothDevice bt : pairedDevices) {
list.add(bt);
popup.getMenu().add(bt.getName());
popup.show();
}
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
ArrayList<BluetoothDevice> deviceArrayList = new ArrayList<BluetoothDevice>(pairedDevices);
Toast.makeText(DeviceList.this, "Testing: " + item.getTitle(), Toast.LENGTH_SHORT).show();
// instrument = deviceArrayList.get(deviceArrayList.indexOf(item.getItemId()));
instrument = deviceArrayList.get(0);
connector = new BluetoothConnection(instrument);
connector.run();
Toast.makeText(DeviceList.this, "Connected to : " + item.getTitle(), Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(DeviceList.this, InputActivity.class);
DeviceList.this.startActivity(myIntent);
return true;
}
});
}
});
btSwitch = (Switch) findViewById(R.id.switch1);
BA =BluetoothAdapter.getDefaultAdapter();
lv =(ListView) findViewById(R.id.listView);
if(BA.isEnabled())
btSwitch.setChecked(true);
else
btSwitch.setChecked(false);
// pMenu = new PopupMenu(this,findViewById(R.id.device_search));
}
public void list(View v){
// pairedDevices = BA.getBondedDevices();
//
// ArrayList list = new ArrayList();
//
// for(BluetoothDevice bt : pairedDevices){
//
// list.add(bt.getName());
// pMenu.getMenu().add(bt.toString());
// }
Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
public void onOff(View v)
{
if(BA.isEnabled())
{
BA.disable();
Toast.makeText(getApplicationContext(), " BT Turned off" ,Toast.LENGTH_LONG).show();
}
else
{ BA.enable();
Toast.makeText(getApplicationContext(), "BT Turned on" ,Toast.LENGTH_LONG).show();
}
}
public static BluetoothDevice getInstrument() {
return instrument;
}
}
this is what is running on the console when I select the device I would like to connect to:
I/System.out: $$$$$$$$$$$$$$$$****** in constructor ******$$$$$$$$$$$$$$$$
D/workkkkkk: $$$$$$$$$$$$$$$$****** printingggggg ******$$$$$$$$$$$$$$$$
D/BluetoothUtils: isSocketAllowedBySecurityPolicy start : device null
D/BluetoothSocket: connect(): myUserId = 0
W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
I/System.out: $$$$$$$$$$$$$$$$****** socket closed ******$$$$$$$$$$$$$$$$
D/BluetoothSocket: getInputStream(): myUserId = 0
getOutputStream(): myUserId = 0
Why is it not connecting in the try?

Manage Bluetooth Communication

Im actually trying to interact with a bluetooth module controlled by a microcontroller PIC.
So i need to build an android app in order to send caracters by bluetooth.
But im kind of lost.
The beginning is quiet clear to me ( enabling bluetooth and connect as client)
But i dont know how to interact with my Bluetooth Service class from my MainActivity.
How to interact with write and read.
I can see that im successfully Connected to my device.
ALEA is the name of the BT module i want to connect to.
Thanks for your help
package com.example.stef.bluetoothencore;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter;
ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
ArrayList<String> NomBT=null;
BluetoothDevice mydevice;
int position_alea=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv=(ListView)findViewById(R.id.listdevice);
CheckBox Aleabox=(CheckBox) findViewById(R.id.checkAlea);
arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
NomBT= new ArrayList<String>();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
BluetoothDevice mDevice = device;
arrayListBluetoothDevices.add(device); // On charge la liste de Device
NomBT.add(device.getName().toString());
if(device.getName().toString().equals("ALEA")){
mydevice=device;
Aleabox.setChecked(true);
Aleabox.setText(mydevice.getName().toString());
}
}
}
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, NomBT);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// position_alea=i;
//Toast.makeText(getApplicationContext(), mydevice.getName().toString(), Toast.LENGTH_SHORT).show();
ConnectThread mConnectThread = new ConnectThread(mydevice);
mConnectThread.start();
}
});
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
mBluetoothAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
ConnectedThread mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
mConnectedThread.write("c".getBytes());
}
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;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int begin = 0;
int bytes = 0;
while (true) {
try {
bytes += mmInStream.read(buffer, bytes, buffer.length - bytes);
for(int i = begin; i < bytes; i++) {
if(buffer[i] == "#".getBytes()[0]) {
mHandler.obtainMessage(1, begin, i, buffer).sendToTarget();
begin = i + 1;
if(i == bytes - 1) {
bytes = 0;
begin = 0;
}
}
}
} catch (IOException e) {
break;
}
}
}
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
byte[] writeBuf = (byte[]) msg.obj;
int begin = (int)msg.arg1;
int end = (int)msg.arg2;
switch(msg.what) {
case 1:
String writeMessage = new String(writeBuf);
writeMessage = writeMessage.substring(begin, end);
break;
}
}
};
}
Up, im still blocked, i am connected to my device but i can't read or write data ...

IOException in Java (Android): Transport endpoint is not connected

In my Android application, which was copied from answer to this question (and then slightly changed due to UUID-related problems with Samsung Galaxy tabs) I successfully connect to OBD device via bluetooth.
Then, when I try to send any command (which is done by sendData()), the exception from the title (Transport endpoint is not connected) is thrown and nothing is sent.
When I connected to my computer (the only difference in code is hardware address), I can send command without any problem (of course, I don't get any response, since computer is not OBD-device). Therefore, I believe I got all the permissions I need and UUID address is fine also.
EDIT1:
I installed Komunikacija.apk on the tablet again. I have only added some comments and have encountered two new problems:
mmSocket.connect() in openBT() fails (nothing happens for a long time after the last toast "5")
if bluetooth is turned off, the application shows a request for turning bluetoot on, but then "unfortunately stops".
EDIT2:
I went to the car again and test the app on Samsung phone and again onf the tablet also. Results:
tablet:
when running the application for the first time, connections, mentioned in EDIT1, wasn't made successfully.
I succeed in all of my next attempts, but IOException was thrown:
when I pressed the button SEND for the first time, exception.getMessage() returned Connection reset by peer
every next time, I got message Transport endpoint is not connected
phone: I successfully made a connection already in the first attempt, everything else was the same
EDIT3:
I found out that the OBD-device EML327 was at least part of the problems, because today, I tested get another OBD-device (OBDLink LX) and everything works fine, if I use it. Now, the question is
Why are those two OBD-devices behaving completely different and how to fix errors which occur, if I use OBD327?
EDIT4: I didn't find this important earlier, but the only response from my EML327 was AT+BRSF=24. After googling it around, I found an answer.
My MainActivity.java:
package com.example.komunikacija;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView myLabel;
EditText myTextbox;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter, stevec;
volatile boolean stopWorker;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button openButton = (Button)findViewById(R.id.open);
Button sendButton = (Button)findViewById(R.id.send);
Button closeButton = (Button)findViewById(R.id.close);
myLabel = (TextView)findViewById(R.id.label);
myTextbox = (EditText)findViewById(R.id.entry);
//Open Button
openButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
try {
findBT();
openBT();
}
catch (IOException ex) { }
}
});
//Send Button
sendButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
try{
sendData();
}
catch (IOException ex) {
Toast.makeText(getApplicationContext(), "error when sending:"+ ex.getMessage(), Toast.LENGTH_SHORT).show();;
}
}
});
//Close button
closeButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
try
{
closeBT();
}
catch (IOException ex) { }
}
});
}
void findBT() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null){
myLabel.setText("No bluetooth adapter available");
}
else{
if (!mBluetoothAdapter.isEnabled()){
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
Toast.makeText(this, "we found "+Integer.toString(pairedDevices.size()), Toast.LENGTH_SHORT).show();//number of devices found
if(pairedDevices.size() > 0){
for(BluetoothDevice device : pairedDevices){
//computer's addres: "00:22:68:E6:7D:D7"
//obd device's("00:0D:18:00:00:01")
//device.getName().equals("MattsBlueTooth")
if(device.getAddress().equals("00:22:68:E6:7D:D7")) {
Toast.makeText(this, "Found.", Toast.LENGTH_SHORT).show();
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
}
}
void openBT() throws IOException{
Toast.makeText(this, "openBT.", Toast.LENGTH_SHORT).show();
// UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID
UUID uuid = mmDevice.getUuids()[0].getUuid();
BluetoothSocket tmp = null;
try {
tmp = mmDevice.createRfcommSocketToServiceRecord(uuid);
// for others devices its works with:
// Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
// for galaxy tab 2 with:
Method m = mmDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(mmDevice, 1);
} catch (IOException e) {
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "1", Toast.LENGTH_SHORT).show();;
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "2", Toast.LENGTH_SHORT).show();;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "3", Toast.LENGTH_SHORT).show();;
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "4", Toast.LENGTH_SHORT).show();;
}
mmSocket = tmp;
Toast.makeText(this, "5", Toast.LENGTH_SHORT).show();;
mmSocket.connect();
// Log.i(TAG, "Client Connected!");
// mmSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(uuid);
Toast.makeText(this, "before connect", Toast.LENGTH_SHORT).show();
// mmSocket.connect();
Toast.makeText(this, "before stream", Toast.LENGTH_SHORT).show();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
Toast.makeText(this, "before listening", Toast.LENGTH_SHORT).show();
beginListenForData();
myLabel.setText("Bluetooth Opened");
}
void beginListenForData(){
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
final byte konec = 90; //ASCII for char Z
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run(){
while(!Thread.currentThread().isInterrupted() && !stopWorker){
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
packetBytes[bytesAvailable - 1] = konec;
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == konec)//originally if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
Toast.makeText(getApplicationContext(), "setting " + Integer.toString(stevec++)+data, Toast.LENGTH_SHORT).show();
myLabel.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
void sendData() throws IOException {
String msg = myTextbox.getText().toString();
Toast.makeText(this, "sending:"+msg, Toast.LENGTH_SHORT).show();;
//msg += "\n"; <-- dont want to have that.
mmOutputStream.write(msg.getBytes());
myLabel.setText("Data Sent");
}
void closeBT() throws IOException {
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
}
}
I didn't just wait and the aswers to questions here and here helped me out of troubles. The problem was that EML327 needed channel 16, so the second argument of the method invoke should be 16.

Receive a string via RFCOMM in android

I am trying to recieve a string via RFCOMM in android
I am a newbie to android and please help me
I can send data
but receiving fails
Here is my code
Please help me
package com.example.btspp;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Scanner;
import java.util.UUID;
import java.util.regex.Pattern;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class Buttons extends Activity {
private BluetoothAdapter btAdaptor;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private InputStream inStream = null;
private static final UUID MY_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
public String addressToConnect;
public static StringBuilder readStr;
TextView tv;
int aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buttons);
tv = (TextView) findViewById(R.id.textView1);
addressToConnect = getIntent().getStringExtra("addressToConnect");
connectToDevice(addressToConnect);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
sendData("H");
// Toast.makeText(getBaseContext(), addressToConnect,
// Toast.LENGTH_SHORT).show();
}
});
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
try {
// final BT bt = new BT();
outStream.write(msgBuffer);
//readData();
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(),
"Not Sent BT Data : " + e.getMessage(), Toast.LENGTH_SHORT)
.show();
}
}
/*private void readData(){
String instring = "";
try {
inStream = btSocket.getInputStream();
} catch (Exception e) {
// TODO: handle exception
}
Scanner scan = new Scanner(new InputStreamReader(inStream));
scan.useDelimiter(Pattern.compile("[\\r\\n]+"));
instring = scan.next();
scan = null;
Toast.makeText(getApplicationContext(),
"Got Data : " + instring, Toast.LENGTH_SHORT)
.show();
//return instring;
}*/
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = inStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
inStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
tv.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
private void connectToDevice(String address) {
btAdaptor = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = btAdaptor.getRemoteDevice(address);
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
outStream = btSocket.getOutputStream();
inStream = btSocket.getInputStream();
beginListenForData();
tv.setText("Bluetooth Opened");
//listenForMessages(btSocket, readStr);
// beginListenForData();
} catch (IOException e) {
// errorExit("Fatal Error",
// "In onResume() and socket create failed: " + e.getMessage() +
// ".");
Toast.makeText(getApplicationContext(),
"Not Connected : " + e.getMessage(), Toast.LENGTH_SHORT)
.show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_buttons, menu);
return true;
}
}
I am a newbie to android and please help me
I can send data
but receiving fails
Here is my code
Please help me
Isn't 13 "\r" the usual delimiter and not 10?

Android Application communication serial data

I am making a Bluetooth app which connects to a Bluetooth transmitter/receiver which is transmitting serial data. The Bluetooth device will eventually be connected to sensors and these sensors will provide data which needs to be displayed on my phone. As of now am using the simulation software CoolTerm to send data back and forth between my app and the external Bluetooth device. Currently I have successfully made the app detect and connect to devices. But I am running into some problems:
Firstly does any one know how to install CoolTerm( its available on Mac and windows technically speaking), but when I try to install it on Ubuntu it gives no executable file like it did on windows. Anyone who knows how to install this on ubuntu please provide me the steps I have already downloaded the Linux version tar ball from there website and unziped it.
Although on successful connection my app sends a string which is received by the Bluetooth device I am not able to receive data back. The way I have things currently set up I expect a toast message to pop-up telling me I have received data when the external Bluetooth device transmits to me. The CoolTerm software allows you to send data but this is for some reason not being displayed on my app. Any ideas?
Lastly anyone know a good text box widget or something I can use in my app to send data to the external Bluetooth device. Right now I have the app send a string as soon as it connects.
Here is a YouTube link: I have made some minor changes to this as the code will suggest.
Click [here](http://www.youtube.com/watch?v=r55C77_ohi8"youtube video of app")!
Click [here](https://drive.google.com/?tab=mo&authuser=0#folders/0BwRY4KO_k7sUSGpLX0o4TDFCOFk"cleaner code formmatt")!
Here is the code
package com.example.intellicyclemobileside;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
ToggleButton toggle_discovery;
Button button;
ListView listView;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
ArrayAdapter<String> mArrayAdapter;
ArrayAdapter<String> adapter;
ArrayList<String> pairedDevicesList;
ArrayList<String> unpairedDevicesList;
ArrayList<String> combinedDevicesList;
Set<BluetoothDevice> pairedDevices;
Set<String> unpairedDevices;
BroadcastReceiver mReceiver;
String selectedFromList;
String selectedFromListName;
String selectedFromListAddress;
BluetoothDevice selectedDevice;
/*
public BluetoothSocket mmSocket;
public BluetoothDevice mmDevice;*/
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
final int STATE_CONNECTED = 2;
final int STATE_CONNECTING = 1;
final int STATE_DISCONNECTED = 0;
private final UUID MY_UUID = UUID.fromString("0001101-0000-1000-8000-00805F9B34FB");
private static final int REQUEST_ENABLE_BT = 1;
Handler mHandler = new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
switch(msg.what){
case SUCCESS_CONNECT:
// Do Something;
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(),"CONNECTED",0).show();
String s = "This string proves a socket connection has been established!!";
connectedThread.write(s.getBytes());
break;
case MESSAGE_READ:
byte[] readBuf = (byte[])msg.obj;
String string = new String(readBuf);
Toast.makeText(getApplicationContext(),string,0).show();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.findDevices);
toggle_discovery = (ToggleButton) findViewById(R.id.deviceDiscoverable);
pairedDevicesList = new ArrayList<String>();
unpairedDevicesList = new ArrayList<String>();
unpairedDevices = new HashSet<String>();
listView = (ListView)findViewById(R.id.listView);
// Sets up Bluetooth
enableBT();
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Toast.makeText(getApplicationContext(), "Searching for devices, please wait... ",Toast.LENGTH_SHORT).show();
// Checks for known paired devices
pairedDevices = mBluetoothAdapter.getBondedDevices();
displayCominedDevices();
//mBluetoothAdapter.cancelDiscovery();
}
});
toggle_discovery.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
makeDicoverable(1);
} else {
// The toggle is disabled
makeDicoverable(0);
}
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// When clicked, show a toast with the TextView text
selectedFromList = (String) (listView.getItemAtPosition(position));
/*Debugging
Toast.makeText(getApplicationContext(), selectedFromList,Toast.LENGTH_SHORT).show();*/
String[] parts = selectedFromList.split(" ");
selectedFromListName = parts[0];
selectedFromListAddress = parts[1];
BluetoothDevice selectedDevice = selectedDevice(selectedFromListAddress);
mBluetoothAdapter.cancelDiscovery();
ConnectThread ct = new ConnectThread(selectedDevice);
ct.start();
//ConnectThread ConnectThread = new ConnectThread(selectedDevice);
//connectDevice();
/* Debug Help
Toast.makeText(getApplicationContext(), selectedFromListName,Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), selectedFromListAddress,Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),selectedDevice.getAddress(), Toast.LENGTH_SHORT).show();*/
}
});
}
public void displayCominedDevices(){
displayPairedDevices();
displayDetectedDevices();
mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,removeDuplicates(unpairedDevicesList,pairedDevicesList));
listView.setAdapter(mArrayAdapter);
}
public BluetoothDevice selectedDevice(String deviceAddress){
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device;
device = mBluetoothAdapter.getRemoteDevice(deviceAddress);
return device;
}
#SuppressLint("NewApi")
public String checkState(BluetoothSocket mmSocket2){
String state = "NOT_KNOWN";
if (mmSocket2.isConnected() == true){
state = "STATE_CONNECTED";
}
state = "STATE_DISCONNECTED";
Toast.makeText(getApplicationContext(), state, Toast.LENGTH_SHORT).show();
return state;
}
#SuppressWarnings("unchecked")
public ArrayList<String> removeDuplicates(ArrayList<String> s1, ArrayList<String> s2){
/*Debugging
Toast.makeText(getApplication(), "unpairedList " + s1.toString(),Toast.LENGTH_LONG).show();
Toast.makeText(getApplication(), "pairedList " + s2.toString(),Toast.LENGTH_LONG).show(); */
combinedDevicesList = new ArrayList<String>();
combinedDevicesList.addAll(s1);
combinedDevicesList.addAll(s2);
#SuppressWarnings("unchecked")
Set Unique_set = new HashSet(combinedDevicesList);
combinedDevicesList = new ArrayList<String>(Unique_set);
/*Debugging
Toast.makeText(getApplication(),"Combined List" + combinedDevicesList.toString(),Toast.LENGTH_LONG).show(); */
return combinedDevicesList;
}
public void enableBT(){
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Toast.makeText(getApplicationContext(), "Bluetooth is not suppourted on Device",Toast.LENGTH_SHORT).show();
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
int resultCode = Activity.RESULT_OK;
if(resultCode < 1){
Toast.makeText(getApplicationContext(), "Please Accept Enabling Bluetooth Request!", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(), "Enabling Bluetooth FAILED!", Toast.LENGTH_SHORT).show();
}
}
}
public void displayPairedDevices(){
// If there are paired devices
enableBT();
if (pairedDevices.size() > 0) {
//Toast.makeText(getApplicationContext(),"in loop",Toast.LENGTH_SHORT).show();
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
String s = " ";
String deviceName = device.getName();
String deviceAddress = device.getAddress();
pairedDevicesList.add(deviceName + s + deviceAddress +" \n");
//listView.setAdapter(mArrayAdapter);
//Toast.makeText(getApplicationContext(), device.getName(),Toast.LENGTH_SHORT).show();
}
/*
mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,pairedDevicesList);
listView.setAdapter(mArrayAdapter);*/
}
}
public void displayDetectedDevices(){
mBluetoothAdapter.startDiscovery();
// Create a BroadcastReceiver for ACTION_FOUND
mReceiver = new BroadcastReceiver() {
#SuppressWarnings("static-access")
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
/* Debugging help
Toast.makeText(getApplicationContext(),action,Toast.LENGTH_SHORT).show();*/
// When discovery finds a device
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
/* Debugging help
Toast.makeText(getApplicationContext(),device.getName(),Toast.LENGTH_SHORT).show();*/
String deviceName = device.getName();
String deviceAddress = device.getAddress();
String s = " ";
unpairedDevices.add(deviceName + s + deviceAddress +" \n");
//unpairedDevicesList.add(deviceName + s + deviceAddress +" (un-paired)\n");
unpairedDevicesList = new ArrayList<String>(unpairedDevices);
}
}
};
/*adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,unpairedDevicesList);
listView.setAdapter(adapter);*/
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
//Toast.makeText(getApplicationContext(), unpairedDevicesList.toString(), Toast.LENGTH_LONG).show();
}
public void makeDicoverable(int option){
Intent discoverableIntent;
if (option == 1){
discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,120);
startActivity(discoverableIntent);
Toast.makeText(getApplicationContext(), "Open discovery for 2mins", Toast.LENGTH_SHORT).show();
} else {
discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 1);
startActivity(discoverableIntent);
Toast.makeText(getApplicationContext(), "Open discovery is OFF!", Toast.LENGTH_SHORT).show();
}
}
/*Un-used Method
public void compareAddress(BluetoothDevice checkDevice,String address){
if((checkDevice.getAddress().equals(address))){
selectedDevice = checkDevice;
}
}*/
#SuppressLint("NewApi")
public class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
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
tmp = device.createRfcommSocketToServiceRecord(MY_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) {
Toast.makeText(getApplicationContext(), "Connecting to device failed!", Toast.LENGTH_LONG).show();
}
return;
}
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** 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; // 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) { }
}
}
}
If your device is a 'Bluetooth to UART converter' module, then, make a loop-back connection at module (i.e. short TXD with RXD). Send test strings from your app to the module and expect to receive it back as well. Depending on results of such test your app or/and module can be probed further to recover real issue, if any.

Categories

Resources