How to Receive Serial Data Using Android Bluetooth

How to receive serial data using android bluetooth

try this code :

Activity:

package Android.Arduino.Bluetooth;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends Activity
{
TextView myLabel;
EditText myTextbox;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button openButton = (Button)findViewById(R.id.open);
Button sendButton = (Button)findViewById(R.id.send);
Button closeButton = (Button)findViewById(R.id.close);
myLabel = (TextView)findViewById(R.id.label);
myTextbox = (EditText)findViewById(R.id.entry);

//Open Button
openButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
findBT();
openBT();
}
catch (IOException ex) { }
}
});

//Send Button
sendButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
sendData();
}
catch (IOException ex) { }
}
});

//Close button
closeButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
closeBT();
}
catch (IOException ex) { }
}
});
}

void findBT()
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null)
{
myLabel.setText("No bluetooth adapter available");
}

if(!mBluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals("MattsBlueTooth"))
{
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
}

void openBT() throws IOException
{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();

beginListenForData();

myLabel.setText("Bluetooth Opened");
}

void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character

stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;

handler.post(new Runnable()
{
public void run()
{
myLabel.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});

workerThread.start();
}

void sendData() throws IOException
{
String msg = myTextbox.getText().toString();
msg += "\n";
mmOutputStream.write(msg.getBytes());
myLabel.setText("Data Sent");
}

void closeBT() throws IOException
{
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
}
}

AND Here the layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:ignore="TextFields,HardcodedText" >

<TextView
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Type here:" />

<EditText
android:id="@+id/entry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/label"
android:background="@android:drawable/editbox_background" />

<Button
android:id="@+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="@id/entry"
android:layout_marginLeft="10dip"
android:text="Open" />

<Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/open"
android:layout_toLeftOf="@id/open"
android:text="Send" />

<Button
android:id="@+id/close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/send"
android:layout_toLeftOf="@id/send"
android:text="Close" />

</RelativeLayout>

Here for Manifest:
add to Application

// permission must be enabled complete
<manifest ....>

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<application>

</application>
</manifest>

How to receive serial data from arduino using bluetooth?

You'll need a HC-05 bluetooth module for example, and the use of the Serial library.
Try to define a new serial port and then send your data by it.
Arduino code :

SoftwareSerial btSerial (12, 13); //TX sur 12 et RX sur 13
btSerial.begin(9600);
btSerial.println("Link Started !");

Send data from an android app to a Serial COM Port via Bluetooth

I had actually 2 problems going on :

  • I had to go in the settings of my Bluetooth dongle and create a Bluetooth COM Port associated with it
  • I had to change in the code the UUID (Universally Unique Identifier): the UUID for the SPP (Serial Port Service) is defined by the Bluetooth SIG to be 0x1101. If you are connecting to a Bluetooth serial board, then try using the "well-known" SPP UUID : 00001101-0000-1000-8000-00805F9B34FB with this code line:

private static final UUID MY_UUID_SECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

(I put the same for both MY_UUID_SECURE and MY_UUID_INSECURE just to check if it was working)

And then this solved my problem. Hope it can help some people who have the same problems.

How do I receive bluetooth data from arduino to android?

Look at this.... very effective. In this code, you take a MAC address by file and connect it to the device automatically. Then you can send and receive string data from Arduino. You can take inspiration from this code.

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Scroller;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;

public class MainActivity extends Activity implements OnSeekBarChangeListener {

public String ultimodato;

////
private static final String TAG = "bluetooth2";
Handler h;
final int RECEIVE_MESSAGE = 1; //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:14:02:13:00:10";
////

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
/* se non esiste il folder, creare il folder */
File folder = new File(Environment.getExternalStorageDirectory() + "/Asiagem");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}

setContentView(R.layout.main);

//LETTURA DA FILE DEL MAC-ADDRESS A CUI CONNETTERSI
try{
String MACFile = readFileAsString("/sdcard/MAC.txt");
if(MACFile==""){
Toast.makeText(this,"Nessun dispositivo salvato, torno alla fase precedente", Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), Home.class);
startActivity(i);
finish();
}else {
address = MACFile;
}
}catch(Exception e){
Toast.makeText(getApplicationContext(),"Errore nella lettura dei dati" , Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), Home.class);
startActivity(i);
finish();
}
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECEIVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
Toast.makeText(getBaseContext(), strIncom, Toast.LENGTH_SHORT).show();
Log.d("INCOME", "INCOME: " + strIncom);

break;
}
};
};

btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();

}


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);
}

@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void SendMessageBT(View v){
//INVIO MESSAGGIO AL BLUETOOTH
mConnectedThread.write("U");
}
@Override
public void onResume() {
super.onResume();

Log.d(TAG, "...onResume - try connect...");

// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);

// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.

try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}

// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();

// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}

// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");

mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();

previousTime = System.currentTimeMillis();

}

@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) {
if(System.currentTimeMillis() - previousTime > 10000){
previousTime = System.currentTimeMillis();
mConnectedThread.write("w");
}

try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECEIVE_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() + "...");
ultimodato=message;
to_send=true;
//connect();
new connect_and_send().execute();
}
}
}

private class connect_and_send extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() { // Fa vedere solo il dialog
super.onPreExecute();
}


@Override
protected Void doInBackground(Void... arg0) {
try {
btSocket.close();
Log.d(TAG, "...ALERT: " + "SOCKET CHIUSA" + "...");
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
Log.d(TAG, "...ALERT: " + "IMPOSSIBILE CHIUDERE SOCKET" + "...");
}

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();
//REINVIA L'ULTIMO DATO

if (to_send==true){
mConnectedThread.write(ultimodato);
to_send=false;
}

previousTime = System.currentTimeMillis();
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
public static String readFileAsString(String filePath) {

String result = "";
File file = new File(filePath);
if ( file.exists() ) {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
char current;
while (fis.available() > 0) {
current = (char) fis.read();
result = result + String.valueOf(current);

}

} catch (Exception e) {
Log.d("TourGuide", e.toString());
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException ignored) {
}
}

}
return result;
}
}

Android getting serial data via bluetooth using UUID

You have got the BluetoothDevice's details using the following part of your code, use this object to communicate to bluetooth device in serial port profile

"

BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

"

the object "device" is the bluetooth device that you want to connect to.
In general the UUID for serial port profile is 00001101-0000-1000-8000-00805F9B34FB

> BluetoothSocket Bsock = null;
> private static final UUID MY_UUID_SPP=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); >InputStream tmpIn = null;
>OutputStream tmpOut = null;
>
>
> try{
>Bsock = device.createRfcommSocketToServiceRecord(MY_UUID_SPP);
> Bsock.connect();
> tmpIn = socket.getInputStream();
>tmpOut = socket.getOutputStream();
>//use input stream and output stream to read and write to dataserially
>
> }catch(IOException e){e.printStackTrace()}


Related Topics



Leave a reply



Submit