Java, accept multiple mac addresses - java

I'm trying to build an android app that loops 5 MAC addresses because there's 5 devices being used but not at the same time but with the same functions.
Currently I'm using this to start the string:
private static String address = "00:06:66:0A:AD:98";
And this to connect that address to the bluetooth adapter:
BluetoothDevice device = btAdapter.getRemoteDevice(address);
I'm a bit of a noob but the rest of the app is working. It sends and receives data from a serial and displays it in a simple fashion.
Any help would be appreciated.
I've attached the whole code for your review, it's based off a tutorial.
package com.example.bluetooth2;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import com.example.bluetooth2.R;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
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.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "Arduino controller";
Button btnOn, btnOff, btnQ, btnTurbo;
TextView txtArduino,txtOther;
Handler h;
final int RECIEVE_MESSAGE = 1; // Status for Handler
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();
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 = "00:06:66:0A:AD:98";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnQ = (Button) findViewById(R.id.btnQ); // button baton status
btnOn = (Button) findViewById(R.id.btnOn); // button LED ON
btnOff = (Button) findViewById(R.id.btnOff); // button LED OFF
btnTurbo = (Button) findViewById(R.id.btnTurbo); // button TURBO
txtArduino = (TextView) findViewById(R.id.txtArduino); // display battery life
txtOther = (TextView) findViewById(R.id.txtOther); // display other information
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
String[] parts = sbprint.split(" "); // split string
String batteryLife = parts[0]; // battery
String otherInfo = parts[1]; // other
sb.delete(0, sb.length()); // and clear
txtArduino.setText(batteryLife); // update TextView
txtOther.setText(otherInfo); // update textOther
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
btnOn.setEnabled(false);
btnTurbo.setEnabled(true);
btnOff.setEnabled(true);
mConnectedThread.write("h"); // Send "1" via Bluetooth
//Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
btnOff.setEnabled(false);
btnTurbo.setEnabled(true);
btnOn.setEnabled(true);
mConnectedThread.write("l"); // Send "0" via Bluetooth
//Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
btnQ.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("?"); // Send "0" via Bluetooth
//Toast.makeText(getBaseContext(), "Baton Status", Toast.LENGTH_SHORT).show();
}
});
btnTurbo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
btnOff.setEnabled(true);
btnTurbo.setEnabled(false);
btnOn.setEnabled(true);
mConnectedThread.write("t"); // Send "t" via Bluetooth
//Toast.makeText(getBaseContext(), "Turbo mode", 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
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() + "...");
}
}
}
}

String[] fiveMacAddresses = {"address1", "address2", "address3", "address4", "address5"};
List<BluetoothDevice> devices = new ArrayList<BluetoothDevice>(fiveMacAddresses.length);
for (String address: fiveMacAddresses) {
devices.add(btAdapter.getRemoteDevice(address));
}
now you have array of devices.

Related

Android Bluetooth Communication call write medthod

I am attempting to use the MyBluetoothService class straight from the Android tutorials and call the write method from the main activity as suggested by the text. I would just like some guidance on how to pass a string from the main activity to the write method and send it to a connected Bluetooth device.
public class MyBluetoothService {
private static final String TAG = "MY_APP_DEBUG_TAG";
private Handler mHandler; // handler that gets info from Bluetooth service
// Defines several constants used when transmitting messages between the
// service and the UI.
private interface MessageConstants {
public static final int MESSAGE_READ = 0;
public static final int MESSAGE_WRITE = 1;
public static final int MESSAGE_TOAST = 2;
// ... (Add other message types here as needed.)
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private byte[] mmBuffer; // mmBuffer store for the stream
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();
} catch (IOException e) {
Log.e(TAG, "Error occurred when creating input stream", e);
}
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "Error occurred when creating output stream", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
mmBuffer = new byte[1024];
int numBytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs.
while (true) {
try {
// Read from the InputStream.
numBytes = mmInStream.read(mmBuffer);
// Send the obtained bytes to the UI activity.
Message readMsg = mHandler.obtainMessage(
MessageConstants.MESSAGE_READ, numBytes, -1,
mmBuffer);
readMsg.sendToTarget();
} catch (IOException e) {
Log.d(TAG, "Input stream was disconnected", e);
break;
}
}
}
// Call this from the main activity to send data to the remote device.
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
// Share the sent message with the UI activity.
Message writtenMsg = mHandler.obtainMessage(
MessageConstants.MESSAGE_WRITE, -1, -1, mmBuffer);
writtenMsg.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Error occurred when sending data", e);
// Send a failure message back to the activity.
Message writeErrorMsg =
mHandler.obtainMessage(MessageConstants.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString("toast",
"Couldn't send data to the other device");
writeErrorMsg.setData(bundle);
mHandler.sendMessage(writeErrorMsg);
}
}
// Call this method from the main activity to shut down the connection.
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close the connect socket", e);
}
}
}
}
this code will help you to find all the devices in the surrounding
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class DeviceList extends AppCompatActivity {
ListView blist;
Button b;
private BluetoothAdapter myBluetooth = null;
private Set<BluetoothDevice> pairedDevices;
public static String EXTRA_ADDRESS = "device_address";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
b=(Button)findViewById(R.id.button);
blist=(ListView)findViewById(R.id.listView);
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if(myBluetooth == null)
{
//Show a mensag. that the device has no bluetooth adapter
Toast.makeText(getApplicationContext(), "Bluetooth Device Not Available", Toast.LENGTH_LONG).show();
//finish apk
finish();
}
else if(!myBluetooth.isEnabled())
{
//Ask to the user turn the bluetooth on
Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnBTon,1);
}
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pairedDevices();
}
});
}
private void pairedDevices()
{
pairedDevices=myBluetooth.getBondedDevices();
ArrayList list=new ArrayList();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice bt : pairedDevices)
{
list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address
}
}
else
{
Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
}
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
blist.setAdapter(adapter);
blist.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked
}
private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener()
{
public void onItemClick (AdapterView<?> av, View v, int arg2, long arg3)
{
// Get the device MAC address, the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Make an intent to start next activity.
Intent i = new Intent(DeviceList.this, ledControl.class);
//Change the activity.
i.putExtra(EXTRA_ADDRESS, address); //this will be received at ledControl (class) Activity
startActivity(i);
}
};
}
this code helps to send the message to the device connected
public class ledControl extends AppCompatActivity {
Button btnOn, btnOff, btnDis;
TextView lumn;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID. Look for it
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent newint = getIntent();
address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS); //receive the address of the bluetooth device
//view of the ledControl
setContentView(R.layout.activity_led_control);
//call the widgtes
btnOn = (Button) findViewById(R.id.button2);
btnOff = (Button) findViewById(R.id.button3);
btnDis = (Button) findViewById(R.id.button4);
lumn = (TextView) findViewById(R.id.lumn);
new ConnectBT().execute(); //Call the class to connect
//commands to be sent to bluetooth
btnOn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
turnOnLed();
//method to turn on
}
});
btnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
turnOffLed(); //method to turn off
}
});
btnDis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Disconnect(); //close connection
}
});
}
private void Disconnect()
{
if (btSocket!=null) //If the btSocket is busy
{
try
{
btSocket.close(); //close connection
}
catch (IOException e)
{ msg("Error");}
}
finish(); //return to the first layout
}
private void turnOffLed()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("F".toString().getBytes());
//Log.e("message",)
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
if (btSocket!=null)
{
try
{
//Toast.makeText(ledControl.this,"oning",Toast.LENGTH_SHORT).show();
btSocket.getOutputStream().write("O".toString().getBytes());
Log.e("message",btSocket.toString());
}
catch (IOException e)
{
msg("Error");
}
}
}
// fast way to call Toast
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(ledControl.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Connected.");
isBtConnected = true;
}
progress.dismiss();
}
}
}

Bluetooth sending all String in one time (not bit by bit only whole byte at once)

In my mobile robot project, which have 2 servo motors to rotate the camera in two planes I want to control them in my android app by rotation the smartphone (through readings yaw/pitch/roll from the smartphone accelometer).
For that I have to send data about this three angles through Bluetooth to Arduino. So for example sample data packet looks like
"Y:100,P:20,R:45"
where [Y-yaw, P-pitch,R-roll]. However, when I try to send this kind of data packet through Bluetooth from my smartphone to Arduino, in Arduino the packet is received bit by bit, so above shown data packet in Serial Port Monitor looks like:
Y
:
1
0
0
etc. (which makes it much harder to read this data and their correct acquisition, because my smartphone sends as well other data to control the direction of mobile robot [engines]).
So if I using smartphone + Bluetooth + Arduino -> it is possible to send a whole packet of data at once, no bit by bit ???
This is the code from Android Studio (about Bluetooth Activity):
package com.samplecompass;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
public class cBluetooth{
public final static String TAG = "BL_4WD";
private static BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private ConnectedThread mConnectedThread;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private final Handler mHandler;
public final static int BL_NOT_AVAILABLE = 1; // ������ ��� Handler
public final static int BL_INCORRECT_ADDRESS = 2;
public final static int BL_REQUEST_ENABLE = 3;
public final static int BL_SOCKET_FAILED = 4;
public final static int RECIEVE_MESSAGE = 5;
cBluetooth(Context context, Handler handler){
btAdapter = BluetoothAdapter.getDefaultAdapter();
mHandler = handler;
if (btAdapter == null) {
mHandler.sendEmptyMessage(BL_NOT_AVAILABLE);
return;
}
}
public void checkBTState() {
if(btAdapter == null) {
mHandler.sendEmptyMessage(BL_NOT_AVAILABLE);
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "Bluetooth ON");
} else {
mHandler.sendEmptyMessage(BL_REQUEST_ENABLE);
}
}
}
public void BT_Connect(String address) {
Log.d(TAG, "...On Resume...");
if(!BluetoothAdapter.checkBluetoothAddress(address)){
mHandler.sendEmptyMessage(BL_INCORRECT_ADDRESS);
return;
}
else{
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.d(TAG, "In onResume() and socket create failed: " + e.getMessage());
mHandler.sendEmptyMessage(BL_SOCKET_FAILED);
return;
}
btAdapter.cancelDiscovery();
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
Log.d(TAG, "In onResume() and unable to close socket during connection failure" + e2.getMessage());
mHandler.sendEmptyMessage(BL_SOCKET_FAILED);
return;
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Log.d(TAG, "In onResume() and output stream creation failed:" + e.getMessage());
mHandler.sendEmptyMessage(BL_SOCKET_FAILED);
return;
}
mConnectedThread = new ConnectedThread();
mConnectedThread.start();
}
}
public void BT_onPause() {
Log.d(TAG, "...On Pause...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
Log.d(TAG, "In onPause() and failed to flush output stream: " + e.getMessage());
mHandler.sendEmptyMessage(BL_SOCKET_FAILED);
return;
}
}
if (btSocket != null) {
try {
btSocket.close();
} catch (IOException e2) {
Log.d(TAG, "In onPause() and failed to close socket." + e2.getMessage());
mHandler.sendEmptyMessage(BL_SOCKET_FAILED);
return;
}
}
}
public void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.i(TAG, "Send data: " + message);
if (outStream != null) {
try {
outStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "In onResume() and an exception occurred during write: " + e.getMessage());
mHandler.sendEmptyMessage(BL_SOCKET_FAILED);
return;
}
} else Log.d(TAG, "Error Send data: outStream is Null");
}
/**
public void write(byte[] bytes) {
try {
outStream.write(bytes);
} catch (IOException e) { System.out.println(e); }
}
**/
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
public ConnectedThread() {
InputStream tmpIn = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = btSocket.getInputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
}
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);
mHandler.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
}
}

How to read and parse data in Java with HandleMessage method?

I am building an android app that will be able to read values from a load sensor. The load sensor is connected to a LCD to display the values of weight applied to the sensor and an Arduino board. I am simply building this app to get the weight values from the LCD/load sensor. I am using HC-06 Bluetooth module, and I am able to connect/pair with this device successfully. The 'MainActivity' activity has a 'get data' button to read the data from the load sensor but anytime It is pressed the app freezes. I have been told by the author of the following tutorial that I need to write some 'Handler' method. I have made an attempt with no luck.
I've been following this tutorial but I'm stuck on reading data
https://wingoodharry.wordpress.com/2014/04/15/android-sendreceive-data-with-arduino-using-bluetooth-part-2/
Here is my code :
package com.proj.splate;
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;
byte[] buffer;
//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
}
Here is my Arduino Code:
#include <LiquidCrystal.h>
int led = 13;
int button = 12;
LiquidCrystal lcd(9, 8, 4, 5, 6, 7);
// Pins used for inputs and outputs********************************************************
float sensorValue1;
float containerValue;
char inbyte = 0;
int flag;
const int numReadings = 50;
int readings[numReadings];
int index = 0;
int total = 0;
int average = 0;
//*******************************************************************************************
void setup()
{
pinMode(led, OUTPUT);
digitalWrite(led, HIGH);
Serial.begin(9600);
for (int thisReading = 0; thisReading < numReadings; thisReading++)
{
readings[thisReading] = 0;
}
lcd.begin(16, 2); //change to 16, 2 for smaller 16x2 screens
lcd.clear();
lcd.print("hello, world!");
delay (1000);
lcd.clear();
delay (500);
}
void loop()
{
digitalWrite(led, HIGH);
readSensor2(); //DONE
printLCD(); //DONE
return;
sendAndroidValues();
//when serial values have been received this will be true
if (Serial.available() > 0)
{
inbyte = Serial.read();
if (inbyte == '0')
{
//LED off
digitalWrite(led, LOW);
}
if (inbyte == '1')
{
//LED on
digitalWrite(led, HIGH);
}
}
//delay by 2s. Meaning we will be sent values every 2s approx
//also means that it can take up to 2 seconds to change LED state
delay(2000);
void readSensor2()
{
total = total - readings[index];
readings[index] = analogRead(A0);
total = total + readings[index];
index = index + 1;
if (index >= numReadings)
{
index = 0;
}
average = total / numReadings;
//sensorValue1 = (analogRead(A0) - 330)* i;
//delay(200);
Serial.println(average);
delay(100);
if( digitalRead(button) == HIGH && flag == 1)
{
flag = 0;
containerValue = 0;
}
else if (digitalRead(button) == HIGH && flag != 1)
{
flag = 1; //when the button is pressed the initially sesnsor
containerValue = sensorValue1;
delay(10);
}
//Serial.println(digitalRead(button));
delay (1000);
}
//sends the values from the sensor over serial to BT module
void sendAndroidValues()
{
//puts # before the values so our app knows what to do with the data
Serial.print('#');
//for loop cycles through 4 sensors and sends values via serial
Serial.print(sensorValue1);
Serial.print('+');
//technically not needed but I prefer to break up data values
//so they are easier to see when debugging
Serial.print('~'); //used as an end of transmission character - used in app for string length
Serial.println();
delay(5000); //added a delay to eliminate missed transmissions
}
void printLCD()
{
lcd.setCursor(4, 0);
lcd.print(" GRAMS ");
lcd.setCursor(4, 1);
lcd.print(sensorValue1);
}
Not sure if this is much of a problem, since it doesn't look like you're doing a ton of work in your handleMessage(Message msg) method, but your Handler is still being created on the main thread. To use a Handler to process background messages, you'll need to pass it a separate Looper. An easy way to to do this would be to use the HandlerThread class to provide your Looper.
Once you do this, however, you'll need to post results back to your UI thread from your handleMessage(Message msg) since you can't modify UI elements (or use Toasts, see your "write" method) from threads other than the main thread (See Activity.runOnUiThread(Runnable runnable)).
Also, you're still using your "ConnectedThread" object as an object by how you're calling your methods from within your onClickListener...so it's not really doing what you're intending it to do in that regard. To verify this, use Looper.myLooper() == Looper.getMainLooper() to see which thread is currently executing. I'd advise more towards the Handler solution suggested above, and posting Runnables for execution.
Lastly, since you're ConnectedThread runs continously in a while(true) loop without pauses, this could be flooding your handler potentially as well.

Android voice recognition and send data via bluetooth to Arduino. How can I send data several times?

I am a newbie of Android. My application uses Voice Recognition, TextToSpeech and send data out via Bluetooth from Android phone (SAMSUNG Galaxy Note | OS: Android 4.1.2) to Arduino. It can send data out only once a time and after it can't send (it through IOException), so application finish(). Below is my code.
Android Code
package com.itcdroid.smarthome;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Locale;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements
TextToSpeech.OnInitListener {
//Tag for logging
private static final String TAG = "ITCDroid";
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket mBluetoothSocket = null;
private OutputStream outStream = null;
//MAC address of remote Bluetooth device
private final String address = "98:D3:31:B4:34:EE";
// UUID that specifies a protocol for generic bluetooth serial communication
//Well known SPP UUID
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private TextToSpeech tts;
private String ttsText;
private TextView txtSpeechInput;
private ImageButton btnSpeak;
private final int REQ_CODE_SPEECH_INPUT = 100;
// Available commands
private static final String[] commands = {"on", "off", "turn on the light", "turn off the light"};
boolean foundCommand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
checkBtState();
tts = new TextToSpeech(this, this);
txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
// hide the action bar
//getActionBar().hide();
//mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//checkBtState();
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
promptSpeechInput();
}
});
}
#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 = mBluetoothAdapter.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 {
mBluetoothSocket = 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.
mBluetoothAdapter.cancelDiscovery();
// Establish the connection. This will block until is connects.
Log.d(TAG, "...Connecting to Remote...");
try {
mBluetoothSocket.connect();
Log.d(TAG, "...Connection established and data link opened...");
} catch(IOException e) {
try {
mBluetoothSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failture" + e2.getMessage() + ".");
}
}
//Create a data stream so we can talk to server.
Log.d(TAG, "...Creating Socket...");
try {
outStream = mBluetoothSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failture: " + 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() + ".");
}
}
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mBluetoothSocket.close();
} catch (IOException e) { }
}
private void checkBtState() {
// TODO Auto-generated method stub
//Check for Bluetooth support and then check to make sure it is turned on
if (mBluetoothAdapter == null) {
errorExit("Fatal Error", "Bluetooth Not supported. Aborting.");
} else {
if (mBluetoothAdapter.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);
}
}
}
/**
* Showing google speech input dialog
* */
private void promptSpeechInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
/**
* Receiving speech input
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
foundCommand = false;
for(String command : commands) {
if(result.contains(command)) {
foundCommand = true;
if(command == "on") {
txtSpeechInput.setText("You say -on-");
ttsText = "The light is turn on now.";
speakOut();
sentData("1");
}
else if(command == "off") {
txtSpeechInput.setText("You say -off-");
ttsText = "The light is turn off now.";
speakOut();
sentData("2");
}
else if(command == "turn on the light") {
txtSpeechInput.setText("You say -turn on the light-");
ttsText = "The light is turn on now.";
speakOut();
sentData("1");
}
else if(command == "turn off the light") {
txtSpeechInput.setText("You say -turn off the light-");
ttsText = "The light is turn off now.";
speakOut();
sentData("2");
}
}
}
if (!foundCommand) {
txtSpeechInput.setText("Unknown what you say");
ttsText = "I don't know what you want!";
speakOut();
}
//txtSpeechInput.setText(result.get(0));
}
break;
}
}
}
#Override
public void onDestroy() {
// Don't forget to shutdown!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
// tts.setPitch(5); // set pitch level
// tts.setSpeechRate(2); // set speech speed rate
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
//btnSpeak.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
//#SuppressWarnings("deprecation")
private void speakOut() {
String text = ttsText;
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
private void sentData(String message) {
// TODO Auto-generated method stub
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Sending data: " + message + "...");
try {
outStream.write(msgBuffer);
outStream.close();
reConnectBT();
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write:" + e.getMessage();
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + "exists on server.\n\n";
errorExit("sentData IOException", msg);
}
}
private void reConnectBT() {
// TODO Auto-generated method stub
Log.d(TAG, "...In reConnectBT - Attempting client connect...");
//Set up a pointer to the remote node using it's address.
BluetoothDevice device = mBluetoothAdapter.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 {
mBluetoothSocket = 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.
mBluetoothAdapter.cancelDiscovery();
// Establish the connection. This will block until is connects.
Log.d(TAG, "...Connecting to Remote...");
try {
mBluetoothSocket.connect();
Log.d(TAG, "...Connection established and data link opened...");
} catch(IOException e) {
try {
mBluetoothSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failture" + e2.getMessage() + ".");
}
}
//Create a data stream so we can talk to server.
Log.d(TAG, "...Creating Socket...");
try {
outStream = mBluetoothSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failture: " + e.getMessage() + ".");
}
}
private void errorExit(String title, String message) {
// TODO Auto-generated method stub
Toast msg= Toast.makeText(getBaseContext(),
title, Toast.LENGTH_SHORT);
msg.show();
finish();
}
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
It seems that you're doing a lot of juggling with connecting and disconnecting from your bluetooth device, which can harm your performance. Another thing you're doing is managing all of the heavy Bluetooth processes directly in your UI thread, which will make your app lock up until the connections complete.
Here's a link to my project's repository, I'm doing simple Bluetooth connections in it and made a BluetoothConnection class as a wrapper for managing the connection state. Feel free to use the source code, but be wary that I'm always actively changing it. If you choose to use it your code, the implementation would go something like this:
InputStream mInputStream;
OutputStream mOutputStream;
BluetoothConnection mConnection = new BluetoothConnection("Connection Name", "98:D3:31:B4:34:EE");
mConnection.setOnConnectStatusChangedListener(this, new onConnectStatusChangedListener() {
#Override
public void onConnect() {
/*
* Connecting to bluetooth takes some time, it won't be ready immediately.
* Set some actions here that let your program know that the connection
* finished successfully. For example,
*/
mInputStream = mConnection.getInputStream();
mOutputStream = mConnection.getOutputStream();
//Use some method of your own to write data
sendDataToBluetoothDevice(mOutputStream);
}
#Override
public void onDisconnect() {
/*
* Same thing applies to disconnecting, set some actions to occur
* when the disconnect is confirmed.
*/
}
}
/*
* Internally, this launches an AsyncTask to handle connecting,
* which is why we need the onConnectStatusChangedListener
* callbacks.
*/
mConnection.connect();
//To disconnect:
mConnection.disconnect();
This should simplify things for you by handling all of the heavy lifting in background processes. As far as reading and writing more than once, as long as you use the InputStream and OutputStream correctly you should be golden.

Receiving Bluetooth Serial Port (Virtual COM Port) data from Android 2.3.3 device in HyperTerminal

I'm developing an Android application which includes Bluetooth SPP Connection. The post on Receiving String from RFCOMM on PC, sent from Android really helped me.
Even my log in Eclipse says 'wrote 6 bytes out of 6' many times and then the socket gets closed. But, I want to receive (whatever I sent) in my PC using Hyperterminal. How do I do that? How to specify Virtual COM Port in code?
I'm using a Samsung SGH-T759 for testing in USB Debugging mode.
Here's my code:
public class BluetoothActivity extends Activity {
private int bluetooth = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
TextView text = (TextView) findViewById(R.id.text);
text.setText("Click on the button to access devices through Bluetooth");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_bluetooth, menu);
return true;
}
public void bluetoothActivate(View view) {
int REQUEST_ENABLE_BT = 1;
int RESULT_ENABLE_BT = 0;
//TextView text = (TextView) findViewById(R.id.text);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
System.out.println("Button clicked...");
if (mBluetoothAdapter == null) {
//txtView.setText("This device does not support Bluetooth");
CharSequence txt = "This device does not support Bluetooth";
Toast toast = Toast.makeText(getApplicationContext(), txt, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else {
//CharSequence text = "Bluetooth is supported!!!";
System.out.println("Bluetooth is supported!!!");
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
onActivityResult(REQUEST_ENABLE_BT, RESULT_ENABLE_BT, enableBtIntent);
}
else
bluetooth = 1;
device_access(view);
}
}
public void device_access(View view) {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
TextView text = (TextView) findViewById(R.id.text);
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
Spinner btDevices = (Spinner) findViewById(R.id.btDevices);
System.out.println("Bluetooth devices...");
if (bluetooth == 1)
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
System.out.println("Bluetooth paired devices...");
final ArrayAdapter<CharSequence> mArrayAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_list_item_1);
ArrayAdapter<CharSequence> deviceName = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_list_item_1);
mArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
deviceName.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
deviceName.add(device.getName());
}
btDevices.setVisibility(1);
btDevices.setAdapter(mArrayAdapter);
//txtView.append("\nPaired Bluetooth Devices Found...");
/*// Create a BroadcastReceiver for ACTION_FOUND
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
*/
String[] dvc = btDevices.getSelectedItem().toString().split("\n");
final UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //UUID for serial connection
String mac = "90:00:4E:DC:41:9D"; //my laptop's mac adress
//mac = dvc[1];
text.append("\n Data sent to " + btDevices.getSelectedItem().toString());
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mac); //get remote device by mac, we assume these two devices are already paired
// Get a BluetoothSocket to connect with the given BluetoothDevice
BluetoothSocket socket = null;
OutputStream out = null;
InputStream inp = null;
//try {
//socket = device.createRfcommSocketToServiceRecord(SERIAL_UUID);
Method m;
try {
m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
socket = (BluetoothSocket) m.invoke(device, 1);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//}catch (IOException e) {}
try {
mBluetoothAdapter.cancelDiscovery();
socket.connect();
out = socket.getOutputStream();
inp = socket.getInputStream();
//now you can use out to send output via out.write
String outputValue = "Hi...\n",inputValue;
byte[] op = outputValue.getBytes(),buffer = null;
int inpBytes;
for (int i=0; i<1000000; i++) {
out.write(op);
out.flush();
}
System.out.println("Data written!!");
/*while (true) {
try {
// Read from the InputStream
inpBytes = inp.read(buffer);
inputValue = buffer.toString();
text.append(inpBytes+ " " + inputValue);
} catch (IOException e) {
}
}*/ }catch (IOException e) {} finally {
try {
socket.close();
System.out.println("Socket closed...");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
I myself solved it. I had to use the listenUsingRfcommWithServiceRecord(NAME,SERIAL_UUID) to register my phone's SPP capability on my laptop. Then, my laptop assigned a COM port for SPP communication with my phone. Then, I specified this port in AccessPort137 (another application similar to hyperterminal and better than that in some aspects) and established communication properly. My working code follows:
package com.example.bluetoothtest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;
import com.example.bluetoothtest.R;
import com.example.bluetoothtest.DynamicGraph;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class BluetoothActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.bluetoothtest.MESSAGE";
public int bluetooth = 0, mState = 0;
public boolean runThread = false;
private TextView text;
public static final UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //UUID for serial connection
public static final int STATE_DISCONNECTED = 0;
public static final int STATE_CONNECTED = 1;
public static final int MESSAGE_READ = 2;
public static final int START_INTENT = 3;
public static final int REQ_CODE_DYNAMIC = 4;
public static BluetoothAdapter mBluetoothAdapter = null;
public static BluetoothDevice device = null;
BluetoothServerSocket mmServerSocket = null;
BluetoothSocket socket = null,finalSocket = null;
OutputStream out = null;
//InputStream aStream = null;
InputStreamReader aReader = null;
BufferedReader mBufferedReader = null;
ConnectedThread con = null;
AcceptThread accept = null;
ConnectThread connect = null;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
if (con != null) {con.cancel(); con = null;}
mState = STATE_DISCONNECTED;
// Start the thread to listen on a BluetoothServerSocket
if (accept!= null) {
accept = null;
}
text = (TextView) findViewById(R.id.text);
text.setText("Click on the button to access devices through Bluetooth");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_bluetooth, menu);
return true;
}
#Override
public void onDestroy(){
super.onDestroy();
runThread = false;
}
public void bluetoothActivate(View view) {
int REQUEST_ENABLE_BT = 1;
int RESULT_ENABLE_BT = 0;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
System.out.println("Button clicked...");
if (mBluetoothAdapter == null) {
CharSequence txt = "This device does not support Bluetooth";
Toast toast = Toast.makeText(getApplicationContext(), txt, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else {
System.out.println("Bluetooth is supported!!!");
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
onActivityResult(REQUEST_ENABLE_BT, RESULT_ENABLE_BT, enableBtIntent);
}
else
bluetooth = 1;
device_access(view);
}
}
public void bluetoothDisconnect(View view) {
runThread = false;
con.cancel();
//connect.cancel();
System.out.println("Connection disconnected");
text.append("\n Connection disconnected");
}
public void device_access(View view) {
System.out.println("Bluetooth devices...");
if (bluetooth == 1) {
//String mac = "F0:08:F1:36:D3:5B"; //my other phone's mac adress
String mac = "90:00:4E:DC:41:9D"; //my laptop's mac adress
//String mac = "A0:4E:04:B8:1D:62";
//mac = dvc[1];
//text.append("\n Data sent to " + btDevices.getSelectedItem().toString());
//device = mBluetoothAdapter.getRemoteDevice(mac); //get remote device by mac, we assume these two devices are already paired
//text.append("device = " + device);
text.append("\n Bluetooth started...");
System.out.println("Bluetooth Started...");
//ensureDiscoverable();
String backup_file = "dynamic_bluetooth.csv";
intent = new Intent(this, DynamicGraph.class);
intent.putExtra(EXTRA_MESSAGE, backup_file);
System.out.println("Dynamic intent about to start...");
/*connect = new ConnectThread(device);
connect.start();*/
CheckBox plotGraph = (CheckBox) findViewById(R.id.plotGraph);
if (plotGraph.isChecked())
startActivityForResult(intent,REQ_CODE_DYNAMIC);
else {
accept = new AcceptThread();
accept.start();
}
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
this.mmDevice = device;
BluetoothSocket tmp1 = null;
try {
tmp1 = device.createRfcommSocketToServiceRecord(SERIAL_UUID);
} catch (IOException e) {
e.printStackTrace();
}
mmSocket = tmp1;
}
#Override
public void run() {
setName("ConnectThread");
mBluetoothAdapter.cancelDiscovery();
try {
mmSocket.connect();
System.out.println("Connected with the device");
} catch (IOException e) {
try {
mmSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return;
}
/*synchronized (PrinterService.this) {
mConnectThread = null;
}*/
//connected(mmSocket, mmDevice);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e("PrinterService", "close() of connect socket failed", e);
}
}
}
private void ensureDiscoverable() {
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
System.out.println("Device set discoverable");
text.append("\n Device set discoverable");
return;
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_READ:
/*byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);*/
//float readM = Float.parseFloat(readMessage);
System.out.println("Into handler...");
String readMessage = (String) msg.obj;
text.append("\n" + readMessage);
try{
float readM = Float.parseFloat(readMessage);
text.append(" " + readM);
}catch (NumberFormatException e) {
text.append(" - Number Format Exception!!");
e.printStackTrace();
}
break;
case START_INTENT:
System.out.println("Dynamic intent about to start...");
//startActivityForResult(intent,REQ_CODE_DYNAMIC);
break;
}
}
};
private class AcceptThread extends Thread {
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
System.out.println("Listening...");
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("SPP", SERIAL_UUID);
}catch (IOException e) {
System.out.println("Listening Failed");
}
mmServerSocket = tmp;
if (mmServerSocket != null)
System.out.println("Server socket established: tmp = " + tmp);
else
System.out.println("Server socket NOT established: tmp = " + tmp);
}
public void run() {
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
//socket = mmServerSocket.accept();
System.out.println("AcceptThread Run");
while (true) {
if ((mmServerSocket != null) && (mState != STATE_CONNECTED)) {
try {
socket = mmServerSocket.accept();
device = socket.getRemoteDevice();
} catch (IOException e) {
System.out.println("Socket not received");
break;
}
if (socket!= null) {
System.out.println("Device Address: " + device.getAddress());
runThread = true;
con = new ConnectedThread(socket);
con.start();
mState = STATE_CONNECTED;
break;
}
}
else {
System.out.println("Code incomplete. Repeat Listening");
break;
}
}
}
finally {
/*try {
con.cancel();
mmServerSocket.close();
System.out.println("Socket closed...");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Server Socket close problem...");
e.printStackTrace();
} */
}
}
public void cancel() {
try {
mmServerSocket.close();
accept.start();
} catch (IOException e) {
}
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024],readBuffer = new byte[1024];
int bytesAvailable,readBufferPosition;
char[] readMsg = new char[8192];
/*try {
aStream = socket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("InputStream problem...");
e.printStackTrace();
}*/
/*aReader = new InputStreamReader( mmInStream );
mBufferedReader = new BufferedReader( aReader );*/
String aString = "---";
System.out.println("Waiting for input...");
/*try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
System.out.println("Sleeping problem...");
e1.printStackTrace();
}*/
while (runThread) {
try {
/*aReader = new InputStreamReader( mmInStream );
mBufferedReader = new BufferedReader( aReader );
//aString = mBufferedReader.readLine();
mBufferedReader.read(readMsg);
aString = new String(readMsg);
readMsg = new char[8192];
System.out.println(aString);*/
aString = "---";
byte delimiter = 'N'; //New line
readBuffer = new byte[1024];
readBufferPosition = 0;
bytesAvailable = mmInStream.read(buffer);
boolean copied = false;
if (bytesAvailable > 0)
System.out.println(bytesAvailable + " bytes available");
else
System.out.println("Bytes not available");
for(int i=0;i<bytesAvailable;i++)
{
byte b = buffer[i];
System.out.println("Byte = "+ b);
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
aString = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
copied= true;
break;
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
/*aString = new String(buffer);
aString = aString.trim();*/
//float rx_data = Float.parseFloat(aString);
System.out.println("aString = " + aString);
/*mHandler.obtainMessage(BluetoothActivity.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();*/
//buffer = new byte[1024];
if (copied && (aString != "---"))
mHandler.obtainMessage(BluetoothActivity.MESSAGE_READ, aString)
.sendToTarget();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("mBufferedReader problem...");
e.printStackTrace();
break;
}
}
//cancel();
/*out = socket.getOutputStream();
//now you can use out to send output via out.write
String outputValue = "Hi...\n",inputValue;
byte[] op = outputValue.getBytes(),buffer = null;
int inpBytes;
for (int i=0; i<1000000; i++) {
out.write(op);
out.flush();
}
System.out.println("Data written!!");
while (true) {
try {
// Read from the InputStream
inpBytes = inp.read(buffer);
inputValue = buffer.toString();
text.append(inpBytes+ " " + inputValue);
} catch (IOException e) {
}
} */
}
public void cancel() {
try {
/*aReader.close();
mBufferedReader.close();*/
runThread = false;
mState = STATE_DISCONNECTED;
mmSocket.close();
mmServerSocket.close();
System.out.println("Socket closed in thread...");
accept = new AcceptThread();
accept.start();
} catch (IOException e) {
System.out.println("Socket close problem...");
}
}
}
}
Uncomment and run the ConnectThread also if you want bi-directional communication. I only had to receive values; so, I've commented it out. But, this thread has to be run in order to establish a COM port for your phone with your laptop. This is because, only when an application like this which uses Bluetooth SPP is run in the phone and tries to pair with the laptop (using this ConnectThread), the laptop will register the SPP capability of the phone. To see this and enable SPP from your laptop's side, do the following:
Right-click on your Bluetooth icon in the taskbar and click on 'Show Bluetooth Devices'.
In the window that opens, find your phone (remember that it must already be paired with your laptop before even running this SPP application), right-click it and go to 'Properties'.
Go to the 'Services' tab and you'll find a new entry called by the name that you provide as the first parameter in the listenUsingRfcommWithServiceRecord() method. For me it's 'SPP'.
Check that new service to enable SPP between your laptop and your phone.
Now, if you check the 'Hardware' tab, a COM port will be specified which you can use in HyperTerminal or any such application and start communicating.
Also, remember that this is NOT possible with Windows 8 yet! Whatever I've mentioned here pertains to Windows 7; I haven't done this in Windows XP even though it will be pretty much the same method.
I hope my solution helps! And, I welcome comments on my (novice) code from experts in these things - after all, I guess StackOverflow is primarily for that purpose.

Categories

Resources