Unable to get Arduino sensor data - java

I am unable to retrieve the data from Arduino. Is there anything wrong with my code? I have tried many different ways to get data from the Arduino but still to no avail.
Android Studio Code
package com.example.a17019501.bluetootharduino;
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.util.Log;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
//Layout//
TextView adapterStatus;
TextView lightValue;
//Bluetooth//
BluetoothAdapter mBluetoothAdapter;
BluetoothDevice mDevice;
Set <BluetoothDevice> pairedDevices;
ConnectThread mConnectThread;
ConnectedThread mConnectedThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapterStatus = findViewById(R.id.tvAdapterStatus);
lightValue = findViewById(R.id.tvLightValue);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
adapterStatus.setText("Device does not support bluetooth");
}
else {
adapterStatus.setText("Device support bluetooth");
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
mDevice = device;
}
}
mConnectThread = new ConnectThread(mDevice);
mConnectThread.start();
Log.i(TAG, "Connect to device: " + mDevice.getName());
}
public 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;
}
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
public class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInstream;
public ConnectedThread(BluetoothSocket socket) {
Log.i(TAG, "Connected Thread");
mmSocket = socket;
InputStream tmpIn = null;
try {
tmpIn = mmSocket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInstream = tmpIn;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = mmInstream.read(buffer);
Log.i(TAG, "Buffer read");
String incomingMsg = new String(buffer, 0, bytes);
mHandler.obtainMessage(1, bytes, -1, buffer);
Log.i(TAG, "InputStream " + incomingMsg);
} catch (IOException e) {
e.printStackTrace();
Log.i(TAG, "Error reading input " + e.getMessage());
}
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
Handler mHandler = new Handler() {
String s;
#Override
public void handleMessage(Message msg) {
switch(msg.what) {
case 1:
s = (String) msg.obj;
if (s!=null) {
lightValue.setText(Integer.parseInt(s));
}
break;
}
}
};
}`
Arduino Code
#include <SoftwareSerial.h>
const int LightSensor = A1; //LightSensor pin at A1
int bluetoothTx = 2; //BTTX at pin 2
int bluetoothRx = 3; //BTRX at pin 3
int sensorValue = 0;
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup() {
Serial.begin(9600); // Begin the serial monitor at 9600bps
bluetooth.begin(9600); // Start bluetooth serial at 9600
}
void loop() {
sensorValue = analogRead(LightSensor);
bluetooth.print(sensorValue);
Serial.println(sensorValue);
delay(2500);
}

Related

How to reestablish a Bluetooth connection after I leave an activity in Android Studio?

I am working on a project that can send and receive Strings to and from an Arduino to control and monitor various sensors and lights. I am running into an issue where once I leave the activity that connects to Bluetooth and then return to that same activity after visiting the home activity I am no longer able to send and receive data. The sending and receiving of strings works perfectly until I leave the activity to go to the home activity and come back.
Here is the Java code for the sensor activity:
package com.example.arduinocontrol;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class uvlight extends AppCompatActivity implements OnClickListener{
private static final int REQUEST_ENABLE_BT = 1;
private CardView uvLight;
//listeners for button presses
Button on, off,clear;
//textbox below buttons
TextView t1,t2,t3;
BluetoothAdapter mBluetoothAdapter;
BluetoothDevice mDevice;
ByteArrayInputStream mSocket;
ConnectedThread mConnectedThread = null;
ConnectThread mConnectThread = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
//Instantiation
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uvlight);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),"BT not supported!", Toast.LENGTH_SHORT).show();
return;
}
if (!mBluetoothAdapter.isEnabled()) {
//opens a window to ask user to turn on bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
mDevice = device;
}
}
mConnectThread = new ConnectThread(mDevice);
mConnectThread.start();
try {
setw();
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressLint("ClickableViewAccessibility")
private void setw() throws IOException {
//text for bluetooth device details
t1=(TextView)findViewById(R.id.textView3);
t2=(TextView)findViewById(R.id.response);
t2.setMovementMethod(new ScrollingMovementMethod());
String name = mDevice.getName().toString();
try {
t1.setText("Connected to: " + name);
} catch (Exception e) {
e.printStackTrace();
}
//links on and off to their element IDs
on=(Button)findViewById(R.id.uvlighton);
off=(Button)findViewById(R.id.uvlightoff);
clear=(Button)findViewById(R.id.clear);
//clears log text
clear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
t2.setText("");
}
});
on.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//sends 'o' char to Arduino
// method to turn on uv light
if(mConnectedThread != null) {
//String sig = "o";
//mConnectedThread.write(sig.getBytes());
int sig = 112;
mConnectedThread.write(sig);
}
}
});
off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
//method to turn off uv light
if(mConnectedThread != null) {
//String sig1 = "f";
//mConnectedThread.write(sig1.getBytes());
int sig = 113;
mConnectedThread.write(sig);
}
}
});
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
//HC-05 unique uuid
private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
try {
//creates RFCOMM socket
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
//shows user they are connected
Toast.makeText(getApplicationContext(), "Connected to your Arduino", Toast.LENGTH_SHORT).show();
//displays bt info in text field
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Unable to connect!", Toast.LENGTH_SHORT).show();
}
mmSocket = tmp;
}
public void run() {
mBluetoothAdapter.cancelDiscovery();
//need the if for this edge case
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
if (mSocket != null) {
mSocket.close();
}
} catch (IOException closeException) {
Toast.makeText(getApplicationContext(), "Unable to connect socket!", Toast.LENGTH_SHORT).show();
}
return;
}
//new connected thread obj
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Thread for bluetooth process
private class ConnectedThread extends Thread {
//copies bt socket for threading
private final BluetoothSocket mmSocket;
//copies input stream obj for threading
private final InputStream mmInStream;
//copies output stream obj for threading
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
//reads from Arduino
#Override
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++) {
//end char for a given message from Arduino
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;
}
}
}
//writes to the output stream (in this case the Arduino)
public void write(/*byte[] bytes*/int num) {
try {
Toast.makeText(getApplicationContext(), "sending bytes", Toast.LENGTH_SHORT).show();
mmOutStream.write(num);
} catch (IOException e) {
e.printStackTrace();
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v)
{
try
{
}
catch (Exception e)
{
//displays toast message
Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//Suppresses an annoying handler lear warning
#SuppressLint("HandlerLeak")
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);
//sends message to homepage to turn cardview red
//string called error contains value of writeMessage
Intent intent = new Intent("errorCode").putExtra("error", writeMessage);
LocalBroadcastManager.getInstance(uvlight.this).sendBroadcast(intent);
//write message to the scrolling textbox
t2.append(writeMessage);
break;
}
}
};
}
Here is the Java code for the home activity:
package com.example.arduinocontrol;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
public class HomeActivity extends AppCompatActivity implements View.OnClickListener {
private CardView airPump, flowMeter, humiditySensor, levelSwitch1, levelSwitch2, lightStrip, phMeter, uvLight, waterPump, solenoidValve, nutrientPump;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//defines cards
airPump = (CardView) findViewById(R.id.airpump);
flowMeter = (CardView) findViewById(R.id.flowmeter);
humiditySensor = (CardView) findViewById(R.id.humiditysensor);
levelSwitch1 = (CardView) findViewById(R.id.levelswitch1);
levelSwitch2 = (CardView) findViewById(R.id.levelswitch2);
lightStrip = (CardView) findViewById(R.id.lightstrip);
phMeter = (CardView) findViewById(R.id.phmeter);
uvLight = (CardView) findViewById(R.id.uvlight);
waterPump = (CardView) findViewById(R.id.waterpump);
solenoidValve = (CardView) findViewById(R.id.solenoidvalve);
nutrientPump = (CardView) findViewById(R.id.nutrientpump);
//click listeners
airPump.setOnClickListener(this);
flowMeter.setOnClickListener(this);
humiditySensor.setOnClickListener(this);
levelSwitch1.setOnClickListener(this);
levelSwitch2.setOnClickListener(this);
lightStrip.setOnClickListener(this);
phMeter.setOnClickListener(this);
uvLight.setOnClickListener(this);
waterPump.setOnClickListener(this);
solenoidValve.setOnClickListener(this);
nutrientPump.setOnClickListener(this);
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter("errorCode"));
}
//turns Uvlight card red when an error is sent
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String errorMsg = intent.getStringExtra("error");
if (errorMsg.equals("-3")){
uvLight.setCardBackgroundColor(0xFFFF0000);
}
}
};
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
#Override
public void onClick(View v) {
Intent i;
//on click opens the new activity
switch(v.getId()){
case R.id.airpump : i = new Intent(this,Airpump.class); startActivity(i); break;
case R.id.flowmeter : i = new Intent(this,Flowmeter.class); startActivity(i); break;
case R.id.humiditysensor : i =new Intent(this,Humiditysensor.class); startActivity(i); break;
case R.id.levelswitch1 : i = new Intent(this,Levelswitch1.class); startActivity(i); break;
case R.id.levelswitch2 : i = new Intent(this,Levelswitch2.class); startActivity(i); break;
case R.id.lightstrip : i = new Intent(this,Lightstrip.class); startActivity(i); break;
case R.id.phmeter : i = new Intent(this,Phmeter.class); startActivity(i); break;
case R.id.uvlight : i = new Intent(this,uvlight.class); startActivity(i); break;
case R.id.waterpump : i = new Intent(this,Waterpump.class); startActivity(i); break;
case R.id.solenoidvalve : i = new Intent(this,solenoidvalve.class); startActivity(i); break;
case R.id.nutrientpump : i = new Intent(this,Nutrientpump.class); startActivity(i); break;
default:break;
}
}
}
I am new to Android Studio and this is the first time I have had to make a multi-threaded application. Thank You.
you can try to extract the Bluetooth connection method into a simple profit class, similar to "local broadcast manager". When "uvlight" on destroy Bluetooth connection will continue to open. Or you can refer to GitHub's excellent open source libraries, such as: https://github.com/akexorcist/BluetoothSPPLibrary 。 I believe you can learn more in it

How do I engage a Bluetooth connection with another device?

I'm working on a app that will connect to a OBD2 device through Bluetooth, but I haven't yet figured out how to connect to a Bluetooth device.
I followed a video tutorial, and am currently following this tutorial with hopefully better luck, but I don't really understand how to implement the code since I can't see the full code (I'm a beginner).
Any help is appreciated!
Image:
(Here's where I want to press on a device and connect to it.)
BluetoothActivity:
package com.example.asabanov.powersupplytool;
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.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
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 BluetoothActivity extends AppCompatActivity implements OnItemClickListener {
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
ArrayAdapter<String> listAdapter;
ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
IntentFilter filter;
BroadcastReceiver receiver;
//String tag = "debugging";
Handler mHandler = new Handler() {
#Override
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(), "Connect", Toast.LENGTH_SHORT).show();
String s = "Successfully connected";
connectedThread.write(s.getBytes());
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String string = new String(readBuf);
Toast.makeText(getApplicationContext(), "Connect", Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
init(); //initiate Bluetooth
if (btAdapter == null) {
Toast.makeText(getApplicationContext(), "No bluetooth detected on this device", Toast.LENGTH_SHORT).show();
finish();
} else {
if (!btAdapter.isEnabled()) {
turnOnBT();
}
pairedDevices=getPairedDevices();
startDiscovery();
}
}
private void startDiscovery() {
btAdapter.cancelDiscovery();
btAdapter.startDiscovery();
}
private void turnOnBT() {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1);
}
private ArrayList getPairedDevices() {
devicesArray = btAdapter.getBondedDevices();
if (devicesArray.size() > 0) {
//add devices in array to list array
for (BluetoothDevice device : devicesArray) {
pairedDevices.add(device.getName() + "\n" + device.getAddress());
}
}
return pairedDevices;
}
private void init() {
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(this);
listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, 0);
listView.setAdapter(listAdapter);
btAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDevices = new ArrayList<String>();
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
devices = new ArrayList<BluetoothDevice>();
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
String s = "";
for (int a = 0; a < pairedDevices.size(); a++) {
if (device.getName().equals(pairedDevices.get(a))) {
s = "Paired";
break;
}
}
// matt-hp (paired)
listAdapter.add(device.getName() + " " + s + " " + "\n" + device.getAddress());
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
//run some code
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//run some code
} else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
if (btAdapter.getState() == btAdapter.STATE_OFF) {
turnOnBT();
}
}
}
};
registerReceiver(receiver, filter);
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(receiver, filter);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, filter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
finish();
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (btAdapter.isDiscovering()) {
btAdapter.cancelDiscovery();
}
if (listAdapter.getItem(position).contains("Paired")) {
BluetoothDevice selectedDevice = devices.get(position);
ConnectThread connect = new ConnectThread(selectedDevice);
connect.start();
Toast.makeText(getApplicationContext(), "Device is paired", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Device is not paired", Toast.LENGTH_SHORT).show();
}
}
private 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
btAdapter.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) {
}
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) {
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
}

Android - Arduino Bluetooth communication

Hi Im new to android studio and java and was hoping to read data from arduino to android.
The plan is to have the button widget on my interface to send signal to the arduino and have my flex sensor send info back to the android via bluetooth.
the bluetooth module i have is HC-06 and this code is designed so that the phone sends a '*' to the arduino and it sends a random value back to the android but i would like that random value to be shown on a textbox on my interface. the change is meant to happen on java ofcourse but im not sure how to do it. Please help.
this is my arduino code first
#include <SoftwareSerial.h>
const int RX_PIN = 2;
const int TX_PIN = 3;
SoftwareSerial serial(RX_PIN, TX_PIN);
char commandChar;
void setup ()
{
serial.begin (9600);
andomSeed(analogRead(0))
}
void loop ()
{
if(serial.available())
{
commandChar = serial.read();
switch(commandChar)
{
case '*':
serial.print(random(1000) + "#");
break;
}
}
}
and here is my code done on android studio:
package com.example.ft.myapplication;
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.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
BluetoothAdapter mBluetoothAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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();
BluetoothDevice mDevice = null;
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
mDevice = device;
}
}
ConnectThread mConnectThread = new ConnectThread(mDevice);
mConnectThread.start();
}
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;
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
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();
}
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() {
String s = "*";
write(s.getBytes());
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) { }
}
}
}

How to pass a separate looper to a thread using HandlerThread class

I have a Handler called 'bluetoothIn' and I want to pass it to a separate looper using the HandlerThread class which will provide the looper. However I need to post the results back to the UI thread from 'handleMessage(Message msg)' since I can't modify UI elements from threads other than the main thread.
Here is my code :
package com.uniproj.senseplate;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
#SuppressWarnings("unused")
public class MainActivity extends Activity {
Button btnscan;
TextView txtArduino, txtString, txtStringLength, calorie;
Handler bluetoothIn;
final int handlerState = 0; //used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket; //= null;
private StringBuilder recDataString = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service - this should work for most devices
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// String for MAC address
private static String address;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Link the buttons and textViews to respective views
btnscan = (Button) findViewById(R.id.scanBtn);
txtString = (TextView) findViewById(R.id.txtString);
txtStringLength = (TextView) findViewById(R.id.testView1);
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
String readMessage = (String) msg.obj;
recDataString.append(readMessage);
int endOfLineIndex = recDataString.indexOf("~");
if (endOfLineIndex > 0) {
String dataInPrint = recDataString.substring(0, endOfLineIndex);
txtString.setText("Data Received = " + dataInPrint);
int dataLength = dataInPrint.length();
txtStringLength.setText("String Length = " + String.valueOf(dataLength));
if (recDataString.charAt(0) == '#')
{
//get sensor value from string between indices 1-20
String weight = recDataString.substring(1, 20);
//update the textviews with sensor values
calorie.setText(weight + "kg");
}
recDataString.delete(0, recDataString.length());
// strIncom =" ";
dataInPrint = " ";
}
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
// Set up onClick listeners for button to scan for data
btnscan.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("0");
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connecetion with BT device using UUID
}
#Override
public void onResume() {
super.onResume();
//Get MAC address from DeviceListActivity via intent
Intent intent = getIntent();
//Get the MAC address from the DeviceListActivty via EXTRA
address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
//create device and set the MAC address
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
}
// Establish the Bluetooth socket connection.
try
{
btSocket.connect();
} catch (IOException e) {
try
{
btSocket.close();
} catch (IOException e2)
{
//insert code to deal with this
}
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
//I send a character when resuming.beginning transmission to check device is connected
//If it is not an exception will be thrown in the write method and finish() will be called
mConnectedThread.write("x");
}
#Override
public void onPause()
{
super.onPause();
try
{
//Don't leave Bluetooth sockets open when leaving activity
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
//Checks that the Android device Bluetooth is available and prompts to be turned on if off
private void checkBTState() {
if(btAdapter==null) {
Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
} else {
if (btAdapter.isEnabled()) {
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
//create new class for connect thread
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
btSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer);
bluetoothIn.obtainMessage(handlerState, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes();//converts entered String into bytes
try {
mmOutStream.write(msgBuffer);//write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failed", Toast.LENGTH_LONG).show();
finish();
}
}
public class BluetoothInHandler extends Handler{
private Looper sLooper = null;
private Handler mWorkerThreadHandler;
final int handlerState = 0; //used to identify handler message
protected class WorkerArgs {
Handler handler;
String input;
String output;
}
public BluetoothInHandler() {
super();
synchronized (BluetoothInHandler.class) {
if (sLooper == null) {
HandlerThread thread = new HandlerThread("AsyncWorker");
thread.start();
sLooper = thread.getLooper();
}
}
mWorkerThreadHandler = new WorkerHandler(sLooper);
}
#Override
public void handleMessage(Message msg) {
if (msg.what == handlerState) {
WorkerArgs args = (WorkerArgs) msg.obj;
String readMessage = args.output;
//your job;
} else {
super.handleMessage(msg);
}
}
public void write(String input) {
WorkerArgs args = new WorkerArgs();
args.handler = this;
args.input = input;
Message message = mWorkerThreadHandler.obtainMessage(handlerState);
message.obj = args;
mWorkerThreadHandler.sendMessage(message);
}
protected class WorkerHandler extends Handler {
public WorkerHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
if (msg.what == handlerState) {
WorkerArgs args = (WorkerArgs) msg.obj;
//the code here run in a thread, not in the ui thread
//do your job like:
byte[] bytes = mmInStream.read(buffer);
args.output = new String(bytes);
Message message = args.handler.obtainMessage(handlerState);
message.obj = args;
message.sendToTarget();
}
}
}
}
}//ConnectedThread End
}
runOnUi might be a good choice for this
runOnUiThread(new Runnable() {
#Override
public void run() {
// Do whatever you need to do on the UI here
}
});
Sorry, I made a mistake. I think the error is causing by the code bluetoothIn.obtainMessage(handlerState, bytes, -1, buffer).sendToTarget();
change to
bluetoothIn.obtainMessage(handlerState, bytes, -1, new String(buffer)).sendToTarget();
Remove the code I wrote. It is no use.

java.io.IOException: bt socket closed, read return: -1

As i am working on OBD Reader Demo .Through my app i am trying to connect obd reader device and my app is installed in Nexus 7.OBD Reader device is connecting to other apps which is available on google play but if i am connecting with my app it is getting error java.io.IOException: bt socket closed, read return: -1 after connection establish .Any suggestions...
=========================================================
**MainActivity:-**
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.virgosys.demo.commands.SpeedObdCommand;
import com.virgosys.demo.commands.engine.EngineRPMObdCommand;
import com.virgosys.demo.commands.fuel.FindFuelTypeObdCommand;
public class MainActivity extends Bluetooth {
#SuppressWarnings("unused")
private Button On, Off, Visible, list;
private BluetoothAdapter BA;
private Set<BluetoothDevice> pairedDevices;
#SuppressWarnings("unused")
private ListView lv;
private BluetoothDevice device;
// private UUID uuid;
// private BluetoothSocketWrapper bluetoothSocket;
private BluetoothSocket socket;
private String deviceAddress;
String RPM, Speed, FuelType;
private TextView uuidTextView, deviceTextView, showRpm, showSpeed,
showFuelType, tv_connection_e, tv_connection_f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showRpm = ((TextView) findViewById(R.id.show_rpm));
showSpeed = ((TextView) findViewById(R.id.txt_speed));
showFuelType = ((TextView) findViewById(R.id.txt_fueltype));
uuidTextView = ((TextView) findViewById(R.id.txt_uuid));
deviceTextView = ((TextView) findViewById(R.id.txt_device));
// tv_connection_e = ((TextView) findViewById(R.id.txt_device));
// tv_connection_f = ((TextView) findViewById(R.id.show_error));
On = (Button) findViewById(R.id.button1);
Off = (Button) findViewById(R.id.button2);
Visible = (Button) findViewById(R.id.button3);
list = (Button) findViewById(R.id.button4);
lv = (ListView) findViewById(R.id.listView1);
BA = BluetoothAdapter.getDefaultAdapter();
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
}
TextView tv_connection_e = (TextView) findViewById(R.id.show_error);
tv_connection_e.setText(log.toString());
} catch (IOException e) {
}
}
public void on(View view) {
if (!BA.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Turned on",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Already on",
Toast.LENGTH_LONG).show();
}
}
#SuppressWarnings("unchecked")
public void list(View view) {
ArrayList deviceStrs = new ArrayList();
final ArrayList devices = new ArrayList();
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDevices = btAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
deviceStrs.add(device.getName() + "\n" + device.getAddress());
devices.add(device.getAddress());
}
}
// show list
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.select_dialog_singlechoice,
deviceStrs.toArray(new String[deviceStrs.size()]));
alertDialog.setSingleChoiceItems(adapter, -1,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
int position = ((AlertDialog) dialog).getListView()
.getCheckedItemPosition();
deviceAddress = (String) devices.get(position);
System.out.println("Device Address-->" + deviceAddress);
/*
* Intent i = new Intent(MainActivity.this,
* SecondActivity.class); i.putExtra("uuid",
* "00001101-0000-1000-8000-00805F9B34FB");
* i.putExtra("deviceAddress", deviceAddress);
* i.putExtra("RPM", RPM); i.putExtra("Speed", Speed);
* startActivity(i);
*/
try {
dothings();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// save deviceAddress
}
});
alertDialog.setTitle("Choose Bluetooth device");
alertDialog.show();
}
#SuppressLint("NewApi")
protected void dothings() throws InterruptedException {
System.out.println("Inside Do things");
System.out.println("Device address in Do things -->" + deviceAddress);
device = BA.getRemoteDevice(deviceAddress);
// UUID SERIAL_UUID = device.getUuids()[0].getUuid();
// uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
System.out.println("Device Name-->" + device.getName());
System.out.println("Device Address-->" + device.getAddress());
System.out.println("Device Bond State-->" + device.getBondState());
System.out.println("Device Type-->" + device.getType());
System.out.println("Device UUIDS-->" + device.getUuids());
ConnectThread t = new ConnectThread(device);
t.start();
showRpm.setText(RPM);
showSpeed.setText(Speed);
showFuelType.setText(FuelType);
uuidTextView.setText("00001101-0000-1000-8000-00805F9B34FB");
deviceTextView.setText(deviceAddress);
}
public void off(View view) {
BA.disable();
Toast.makeText(getApplicationContext(), "Turned off", Toast.LENGTH_LONG)
.show();
}
public void visible(View view) {
Intent getVisible = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible, 0);
}
#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;
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final UUID WELL_KNOWN_UUID = UUID
.fromString("00001101-0000-1000-8000-00805f9b34fb");
private Object e;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,because
// mmSocket is final
BluetoothSocket tmp = null;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(WELL_KNOWN_UUID);
// This is the trick
Method m = device.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
tmp = (BluetoothSocket) m.invoke(device, 1);
} catch (Exception e) {
e.printStackTrace();
}
mmSocket = tmp;
}
public void run() {
System.out.println("Trying to connect...");
// Cancel discovery because it will slow down the connection
BA.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
System.out.println("Connection established");
// tv_connection_e.setText(e.print.stacktrace);
ConnectedThread tc = new ConnectedThread(mmSocket);
tc.start();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
System.out.println("Fail to connect!");
try {
mmSocket.close();
} catch (IOException closeException) {
System.out.println("Fail to close connection");
}
return;
}
}
/** 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;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
System.out.println("Inside the thread");
mmInStream = tmpIn;
mmOutStream = tmpOut;
try {
EngineRPMObdCommand engineRpmCommand = new EngineRPMObdCommand();
SpeedObdCommand speedCommand = new SpeedObdCommand();
FindFuelTypeObdCommand fueltypeCommand = new FindFuelTypeObdCommand();
System.out.println("Inside the try block");
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Inside while");
// TODO handle commands result
Log.d("Poonam",
"RPM: " + engineRpmCommand.getFormattedResult());
Log.d("Poonam",
"Speed: " + speedCommand.getFormattedResult());
Log.d("Poonam",
"FuelType: " + fueltypeCommand.getFormattedResult());
RPM = engineRpmCommand.getFormattedResult();
Speed = speedCommand.getFormattedResult();
FuelType = fueltypeCommand.getFormattedResult();
try {
engineRpmCommand.run(mmInStream, mmOutStream);
speedCommand.run(mmInStream, mmOutStream);
fueltypeCommand.run(mmInStream, mmOutStream);
System.out.println("Commands Processed");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("outside try catch");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("inside catch before while");
}
// Get the input and output streams, using temp objects because
// member streams are final
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) {
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
}
**Bluetooth.java**
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.ArrayList;
import java.util.List;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
public class Bluetooth extends Activity{
private BluetoothSocketWrapper bluetoothSocket;
private BluetoothDevice device;
private boolean secure;
private BluetoothAdapter adapter;
private List<UUID> uuidCandidates;
private int candidate;
/**
* #param device the device
* #param secure if connection should be done via a secure socket
* #param adapter the Android BT adapter
* #param uuidCandidates a list of UUIDs. if null or empty, the Serial PP id is used
* #return
*/
public void BluetoothConnector(BluetoothDevice device, boolean secure, BluetoothAdapter adapter,
List<UUID> uuidCandidates) {
this.device = device;
this.secure = secure;
this.adapter = adapter;
this.uuidCandidates = uuidCandidates;
if (this.uuidCandidates == null || this.uuidCandidates.isEmpty()) {
this.uuidCandidates = new ArrayList<UUID>();
this.uuidCandidates.add(UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"));
}
}
public BluetoothSocketWrapper connect() throws IOException {
boolean success = false;
while (selectSocket()) {
adapter.cancelDiscovery();
try {
bluetoothSocket.connect();
success = true;
break;
} catch (IOException e) {
//try the fallback
try {
bluetoothSocket = new FallbackBluetoothSocket(bluetoothSocket.getUnderlyingSocket());
Thread.sleep(500);
bluetoothSocket.connect();
success = true;
break;
} catch (FallbackException e1) {
Log.w("BT", "Could not initialize FallbackBluetoothSocket classes.", e);
} catch (InterruptedException e1) {
Log.w("BT", e1.getMessage(), e1);
} catch (IOException e1) {
Log.w("BT", "Fallback failed. Cancelling.", e1);
}
}
}
if (!success) {
throw new IOException("Could not connect to device: "+ device.getAddress());
}
return bluetoothSocket;
}
private boolean selectSocket() throws IOException {
if (candidate >= uuidCandidates.size()) {
return false;
}
BluetoothSocket tmp = null;
UUID uuid = uuidCandidates.get(candidate++);
Log.i("BT", "Attempting to connect to Protocol: "+ uuid);
if (secure) {
Method m = null;
try {
m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
tmp = (BluetoothSocket) m.invoke(device, 1);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
tmp = device.createInsecureRfcommSocketToServiceRecord(uuid);
}
bluetoothSocket = new NativeBluetoothSocket(tmp);
return true;
}
public static interface BluetoothSocketWrapper {
InputStream getInputStream() throws IOException;
OutputStream getOutputStream() throws IOException;
String getRemoteDeviceName();
void connect() throws IOException;
String getRemoteDeviceAddress();
void close() throws IOException;
BluetoothSocket getUnderlyingSocket();
}
public static class NativeBluetoothSocket implements BluetoothSocketWrapper {
private BluetoothSocket socket;
public NativeBluetoothSocket(BluetoothSocket tmp) {
this.socket = tmp;
}
#Override
public InputStream getInputStream() throws IOException {
return socket.getInputStream();
}
#Override
public OutputStream getOutputStream() throws IOException {
return socket.getOutputStream();
}
#Override
public String getRemoteDeviceName() {
return socket.getRemoteDevice().getName();
}
#Override
public void connect() throws IOException {
socket.connect();
}
#Override
public String getRemoteDeviceAddress() {
return socket.getRemoteDevice().getAddress();
}
#Override
public void close() throws IOException {
socket.close();
}
#Override
public BluetoothSocket getUnderlyingSocket() {
return socket;
}
}
public class FallbackBluetoothSocket extends NativeBluetoothSocket {
private BluetoothSocket fallbackSocket;
public FallbackBluetoothSocket(BluetoothSocket tmp) throws FallbackException {
super(tmp);
try
{
Class<?> clazz = tmp.getRemoteDevice().getClass();
Class<?>[] paramTypes = new Class<?>[] {Integer.TYPE};
Method m = clazz.getMethod("createRfcommSocket", paramTypes);
Object[] params = new Object[] {Integer.valueOf(1)};
fallbackSocket = (BluetoothSocket) m.invoke(tmp.getRemoteDevice(), params);
}
catch (Exception e)
{
throw new FallbackException(e);
}
}
#Override
public InputStream getInputStream() throws IOException {
return fallbackSocket.getInputStream();
}
#Override
public OutputStream getOutputStream() throws IOException {
return fallbackSocket.getOutputStream();
}
#Override
public void connect() throws IOException {
fallbackSocket.connect();
}
#Override
public void close() throws IOException {
fallbackSocket.close();
}
}
public static class FallbackException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public FallbackException(Exception e) {
super(e);
}
}
}
(MainActivity.java:367)
try {
engineRpmCommand.run(mmInStream, mmOutStream);
speedCommand.run(mmInStream, mmOutStream);
fueltypeCommand.run(mmInStream, mmOutStream);
System.out.println("Commands Processed");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
367--> e.printStackTrace();
}
System.out.println("outside try catch");
}
(ObdCommand.java:164)
protected void readRawData(InputStream in) throws IOException {
byte b = 0;
StringBuilder res = new StringBuilder();
// read until '>' arrives
164--> while ((char) (b = (byte) in.read()) != '>')
res.append((char) b);
Have you checked if your string builder / buffer contains anything at the time the exception is thrown?
I've had this trouble with Bluetooth on a Nexus 7 2012 and the only thing I can suggest is that you Thread.sleep() while waiting for data and use .available() from the stream to make sure you don't read more than what is available.
You could sleep loop while .available() is zero and not equal to the amount as the last loop, and then assume you have all the data when it stabilizes. Alternatively you can simply catch the exception and assume you have received all the data at that point.
I think its a bug in read() method. From #Keilaron's answer.. I tried this and this works:
while (inputStream.available() == 0);
val available = inputStream.available()
val bytes = ByteArray(available)
inputStream.read(bytes, 0, available)
val text = String(bytes)

Categories