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.
Related
package com.example.yj.bluetoothapplication;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
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.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "bluetooth2";
Button btnLed1, btnLed2, btnLed3, btnpado;
TextView txtArduino;
RelativeLayout rlayout;
Handler h;
final int RECIEVE_MESSAGE = 1; // Status for Handler
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();
private static int flag = 0;
private ConnectedThread mConnectedThread;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "98:D3:61:FD:59:9D";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLed1 = (Button) findViewById(R.id.btnLed1);
btnLed2 = (Button) findViewById(R.id.btnLed2);
btnLed3 = (Button) findViewById(R.id.btnLed3);
btnpado = (Button) findViewById(R.id.btnPado);
txtArduino = (TextView) findViewById(R.id.txtArduino);
rlayout = (RelativeLayout) findViewById(R.id.layout);
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE:
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1);
sb.append(strIncom);
int endOfLineIndex = sb.indexOf("\r\n");
if (endOfLineIndex > 0) {
String sbprint = sb.substring(0, endOfLineIndex);
sb.delete(0, sb.length());
txtArduino.setText("Data from Arduino: " + sbprint);
if(flag%4==3){
rlayout.setBackgroundColor(Color.rgb(255, 255, 255));
}
else if(flag%4==1){
rlayout.setBackgroundColor(Color.rgb(255, 0, 0));
}
else if(flag%4==2){
rlayout.setBackgroundColor(Color.rgb(0, 255, 0));
}
else if(flag%4==0){
rlayout.setBackgroundColor(Color.rgb(0, 0, 255));
}
flag++;
btnLed1.setEnabled(true);
btnLed2.setEnabled(true);
btnLed3.setEnabled(true);
btnpado.setEnabled(true);
}
break;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
btnLed1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("1");
Toast.makeText(getBaseContext(), "Turn on First LED", Toast.LENGTH_SHORT).show();
}
});
btnLed2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("2");
//Toast.makeText(getBaseContext(), "Turn on Second LED", Toast.LENGTH_SHORT).show();
}
});
btnLed3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("3");
//Toast.makeText(getBaseContext(), "Turn on Third LED", Toast.LENGTH_SHORT).show();
}
});
btnpado.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("0");
//Toast.makeText(getBaseContext(), "Turn on all LEDs", Toast.LENGTH_SHORT).show();
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket 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[256]; // 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); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
}
D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket#d1bd8ab, channel: 1, mSocketIS: android.net.LocalSocketImpl$SocketInputStream#218b08, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream#6d4d2a1mSocket: android.net.LocalSocket#a50ecc6 impl:android.net.LocalSocketImpl#3bd5487 fd:java.io.FileDescriptor#ec84fb4, mSocketState: CONNECTED D/ViewRootImpl#3a2e96b[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 0 1 D/InputMethodManager: prepareNavigationBarInfo() DecorView#a62bffa[MainActivity] getNavigationBarColor() -855310 D/InputTransport: Input channel destroyed: fd=76 W/libEGL: EGLNativeWindowType 0x7d358f2010 disconnect failed D/OpenGLRenderer: eglDestroySurface = 0x7d1f6ac180, 0x7d358f2000 D/ViewRootImpl#3a2e96b[MainActivity]: Relayout returned: old=[0,0][1080,2280] new=[0,0][1080,2280] result=0x5 surface={valid=false 0} changed=true D/ViewRootImpl#3a2e96b[MainActivity]: setWindowStopped(true) old=false D/ViewRootImpl#3a2e96b[MainActivity]: Surface release. android.view.WindowManagerGlobal.setStoppedState:669 android.app.Activity.performStop:7647 android.app.ActivityThread.callActivityOnStop:4378 android.app.ActivityThread.performStopActivityInner:4356 android.app.ActivityThread.handleStopActivity:4431 android.app.servertransaction.StopActivityItem.execute:41 android.app.servertransaction.TransactionExecutor.executeLifecycleState:145 android.app.servertransaction.TransactionExecutor.execute:70 D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket#f21e178, channel: 1, mSocketIS: android.net.LocalSocketImpl$SocketInputStream#eefc051, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream#853c0b6mSocket: null, mSocketState: CLOSED Process 30538 terminated.
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?
This question already has answers here:
"R cannot be resolved to a variable"? [duplicate]
(30 answers)
Closed 9 years ago.
Here's my code:
package com.example.connecttest;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import com.example.bttest.R;
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.widget.TextView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
public class ConnectTest extends Activity {
TextView out;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// Well known SPP UUID
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Insert your server's MAC address
private static String address = "00:00:00:00:00:00";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
out = (TextView) findViewById(R.id.out);
out.append("\n...In onCreate()...");
btAdapter = BluetoothAdapter.getDefaultAdapter();
CheckBTState();
}
#Override
public void onStart() {
super.onStart();
out.append("\n...In onStart()...");
}
#Override
public void onResume() {
super.onResume();
out.append("\n...In onResume...\n...Attempting client connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
try {
btSocket.connect();
out.append("\n...Connection established and data link opened...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
out.append("\n...Sending message to server...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
String message = "Hello from Android.\n";
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
AlertBox("Fatal Error", msg);
}
}
#Override
public void onPause() {
super.onPause();
out.append("\n...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
AlertBox("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
AlertBox("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
#Override
public void onStop() {
super.onStop();
out.append("\n...In onStop()...");
}
#Override
public void onDestroy() {
super.onDestroy();
out.append("\n...In onDestroy()...");
}
private void CheckBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
AlertBox("Fatal Error", "Bluetooth Not supported. Aborting.");
} else {
if (btAdapter.isEnabled()) {
out.append("\n...Bluetooth is enabled...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
public void AlertBox( String title, String message ){
new AlertDialog.Builder(this)
.setTitle( title )
.setMessage( message + " Press OK to exit." )
.setPositiveButton("OK", new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
}).show();
}
}
This code has errors recurring every time the importing of R class comes up.
import com.example.bttest.R;
shows that the import cannot be resolved.
setContentView(R.layout.main);
and
out = (TextView) findViewById(R.id.out);
shows that R cannot be resolved to a variable.
Please suggest something to get this working.
Delete the "gen" folder in your project, clean and rebuild. R.java is generated automatically on build
Im new in Android developer. I try create a simple app which is turn on and off LED. Then, I install in my Android phone it work. But when I click the On or Off button it said:
Fatal error- In onResume() and an exception occured during write:socket close.
Hopefully someone help me change my code.
Here my code:
package com.example.ledonoff;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import com.example.ledonoff.R;
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.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class Main extends Activity {
private static final String TAG = "Main";
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// Well known SPP UUID
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Insert your server's MAC address
private static String address = "50:F5:20:42:7F:2B";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "In onCreate()");
setContentView(R.layout.activity_main);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
}
public void buttonOn(View v) {
sendData("1");
Toast msg = Toast.makeText(getBaseContext(),"LED On", Toast.LENGTH_SHORT);
msg.show();
}
public void buttonOff(View v) {
sendData("0");
Toast msg = Toast.makeText(getBaseContext(),"LED Off", Toast.LENGTH_SHORT);
msg.show();
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...In onResume - Attempting client connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting to Remote...");
try {
btSocket.connect();
Log.d(TAG, "...Connection established and data link opened...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Creating Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth Not supported. Aborting.");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth is enabled...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
private void errorExit(String title, String message){
Toast msg = Toast.makeText(getBaseContext(),
title + " - " + message, Toast.LENGTH_SHORT);
msg.show();
finish();
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Sending data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I suppose it's because you get an exception while connecting btSocket, then in the exception handler you catch another exception for btSocket.close() (you can not close it if connect() failed)
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).