Bluetooth send a text to other device - android

i have a simple question:
first, this is all my code:
package com.example.mybluetoothapp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
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.os.Bundle;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
List<BluetoothDevice> devices = new ArrayList<BluetoothDevice>();
BroadcastReceiver broadcastReceiver;
BluetoothAdapter bluetoothAdapter;
public UUID serverUuid = UUID.fromString("SERVEUR");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Votre appareil n'a pas de Bluetooth",
Toast.LENGTH_LONG).show();
finish();
}
if (!bluetoothAdapter.isEnabled()) {
Intent bluetoothIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(bluetoothIntent, 1);
}
Set<BluetoothDevice> pairedDevices = bluetoothAdapter
.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice bluetoothDevice : pairedDevices) {
devices.add(bluetoothDevice);
}
}
broadcastReceiver = 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);
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(broadcastReceiver, filter);
Intent dicoverableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
dicoverableIntent.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(dicoverableIntent);
}
#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
protected void onDestroy() {
unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
private class AcceptThread extends Thread {
BluetoothServerSocket bluetoothServerSocket;
public AcceptThread() {
BluetoothServerSocket serverSocketTmp = null;
try {
serverSocketTmp = bluetoothAdapter
.listenUsingRfcommWithServiceRecord("Bluetooth APP",
serverUuid);
bluetoothServerSocket = serverSocketTmp;
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
BluetoothSocket socket = null;
while (true) {
try {
socket = bluetoothServerSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
if (socket != null) {
// TODO: Managed Connection
// TODO: Envoyer Bonjour et Bienvenue
try {
bluetoothServerSocket.close();
break;
} catch (IOException e) {
e.printStackTrace();
}
}
}
super.run();
}
private void cancel() {
try {
bluetoothServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class ConnectThread extends Thread {
BluetoothSocket socket;
BluetoothDevice device;
public ConnectThread(BluetoothDevice device) {
this.device = device;
BluetoothSocket socketTmp = null;
try {
socketTmp = device
.createRfcommSocketToServiceRecord(serverUuid);
socket = socketTmp;
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
bluetoothAdapter.cancelDiscovery();
try {
socket.connect();
} catch (IOException e) {
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
return;
}
// TODO: Manage connection
super.run();
}
private void cancel() {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class ConnectedThread extends Thread {
private BluetoothSocket bluetoothSocket;
InputStream inputStream = null;
OutputStream outputStream = null;
public ConnectedThread(BluetoothSocket socket) {
bluetoothSocket = socket;
InputStream inputStreamTmp = null;
OutputStream outputStreamTmp = null;
try {
inputStreamTmp = bluetoothSocket.getInputStream();
outputStreamTmp = bluetoothSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
inputStream = inputStreamTmp;
outputStream = outputStreamTmp;
}
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = inputStream.read(buffer);
// TODO: Envoyer message à l'affichage
} catch (IOException e) {
e.printStackTrace();
break;
}
}
super.run();
}
public void write(byte[] bytes) {
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
i get this code from a website, so please how i can us it to send a 'hello world' bettween two smartphone ?
please i need help
thank you

Use the ConnectedThread:
How to send any data.
//Code to send text
String text = "Example";
mConnectedThread.write(text.getBytes());
How to receive the sent text (array length is 1024 and 1024 bytes is 1 KB), modify the run() method in ConnectedThread
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = inputStream.read(buffer);
//Received text is here
String text = new String(buffer, 0, bytes);
Log.d(TAG, text);
} catch (IOException e) {
e.printStackTrace();
break;
}
}
super.run();
}
After checking your code, it seems the threads haven't been started

Related

Android: #Override handleMessage not being called

So I am about to pull my own skin off of my face this has been frustrating me so long. I am trying to capture data sent over Bluetooth and the Handler's handleMessage() method does not fire. Can anyone help?
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.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String BT_UUID = "a2cd7958-5745-450c-9dfc-48ad58ca8d95";
private static final int MESSAGE_READ = 999;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothDevice mDevice;
private BluetoothSocket mBluetoothSocket;
private Handler mConnectionHandler;
private RelativeLayout mConnectionLayout;
private static MainActivity mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
mDevice = intent.getParcelableExtra("device");
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mConnectionLayout = (RelativeLayout)findViewById(R.id.connection_overlay);
mContext = this;
}
#Override
public void onResume() {
super.onResume();
attemptBluetoothConnection();
}
public void attemptBluetoothConnection() {
UUID uuid = UUID.fromString(BT_UUID);
try {
mBluetoothSocket = mDevice.createInsecureRfcommSocketToServiceRecord(uuid);
Log.v("[bluetooth]", "creating RF Comm channel...");
} catch (IOException e) {
e.printStackTrace();
mBluetoothSocket = null;
}
new Handler().post(new Runnable() {
#Override
public void run() {
if (mBluetoothSocket != null) {
Log.v(TAG, "socket not null, attempting connection...");
try {
mBluetoothSocket.connect();
Log.d(TAG, "Connection made!");
mConnectionLayout.setVisibility(View.GONE);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
try {
Log.v(TAG, "Trying fallback");
mBluetoothSocket = (BluetoothSocket) mDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[]{int.class}).invoke(mDevice, 1);
mBluetoothSocket.connect();
mConnectionLayout.setVisibility(View.GONE);
mConnectionHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
Log.v(TAG, "[handleMessage]");
switch (msg.what) {
case MESSAGE_READ:
String data = new String((byte[])msg.obj, 0, msg.arg1);
Log.v(TAG, "Received Data: (" + data.length() + ") " + data);
}
}
};
mConnectionHandler.post(new ConnectedThread(mBluetoothSocket));
Log.v(TAG, "Connection made!");
} catch (Exception e2) {
e2.printStackTrace();
}
Log.d("Connection not made...", "");
}
} else {
Log.v("[bluetooth]", "socket is null...");
}
}
});
}
public 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 = 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) {
Log.v(TAG, "Reading InputStream...");
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
Log.v(TAG, "Sending to " + mConnectionHandler.obtainMessage().getTarget().toString());
mConnectionHandler.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) { }
}
}
}
This code worked perfectly up until I moved it into it's own separate activity when this started happening. Any help is appreciated. Thanks.

Android insecure bluetooth connection

I want to connect android mobile to one electronic device,but I want to connect it insecurely.but its giving me the error of "java.io.IOException: read failed, socket might closed or timeout, read ret: -1"
here is my code
package net.londatiga.android.bluetooth;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
public class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final UUID WELL_KNOWN_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
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);
tmp = device
.createRfcommSocketToServiceRecord(WELL_KNOWN_UUID);
Object[] params = new Object[] {Integer.valueOf(1)};
// This is the trick
Method m = device.getClass().getMethod("createInsecureRfcommSocket",
new Class[] { int.class });
tmp = (BluetoothSocket) m.invoke(device, params);
} catch (Exception e) {
e.printStackTrace();
}
mmSocket = tmp;
}
#SuppressLint("NewApi")
public void run() {
// DebugLog.i(TAG, "Trying to connect...");
// Cancel discovery because it will slow down the connection
MainActivity.mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
boolean val=mmSocket.isConnected();
Log.v("val", ""+val);
// DebugLog.i(TAG, "Connection stablished");
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
// DebugLog.e(TAG, "Fail to connect!", connectException);
try {
mmSocket.close();
} catch (IOException closeException) {
// DebugLog.e(TAG, "Fail to close connection", closeException);
}
return;
}
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
You have to implement an another thread, like below, which always receives your calls and does operations. Start this thread when you start the application.
class AcceptThread extends
Thread {
private final BluetoothServerSocket serverSocket;
private boolean flag = true;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
tmp = bluetoothAdapter
.listenUsingInsecureRfcommWithServiceRecord(
NAME_UUID, uuid);
} catch (IOException e) {
}
serverSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
while (true) {
try {
socket = serverSocket.accept();
if (socket.isConnected()) {
Log.d(TAG, "run: connection successfull");
Log.d(TAG, "run: " + socket.getRemoteDevice().getName() + " " +
socket.getRemoteDevice().getAddress());
}
} catch (IOException e) {
try {
socket.close();
} catch (Exception eee) {
Log.d(TAG, "run: " + eee.getMessage());
}
break;
}
}
}
public void cancel() {
try {
serverSocket.close();
} catch (IOException e) {
}
}
}

Android App to print from a bluetooth printer

The app I have found online works flawlessly except when clicking onto the Send Button, after typing something into the textbox, the printer runs, and stops in the middle of the process of printing, program doesn't crash however. I'm just curious if I'm using the wrong UUID, in fact I don't even know what it is. I have this following class, which is the only class needed to run the app, the rest are XML, with all three bluetooth permissions;
package com.example.bluetoothprinter;
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 {
// will show the statuses
TextView myLabel;
// will enable user to enter any text to be printed
EditText myTextbox;
// android built in classes for bluetooth operations
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.activity_main);
try {
// we are goin to have three buttons for specific functions
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 bluetooth connection
openButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
findBT();
openBT();
} catch (IOException ex) {
}
}
});
// send data typed by the user to be printed
sendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
sendData();
} catch (IOException ex) {
}
}
});
// close bluetooth connection
closeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
closeBT();
} catch (IOException ex) {
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* This will find a bluetooth printer device
*/
void findBT() {
try {
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) {
// OJL411MY29I911JH is the name of the bluetooth printer device shown after scan
if (device.getName().equals("OJL411MY29I911JH")) {
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Tries to open a connection to the bluetooth printer device
*/
void openBT() throws IOException {
try {
// Standard SerialPortService ID
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
myLabel.setText("Bluetooth Opened");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* After opening a connection to bluetooth printer device,
* we have to listen and check if a data were sent to be printed.
*/
void beginListenForData() {
try {
final Handler handler = new Handler();
// This is the ASCII code for a newline character
final byte delimiter = 10;
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();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* This will send data to be printed by the bluetooth printer
*/
void sendData() throws IOException {
try {
// the text typed by the user
String msg = myTextbox.getText().toString();
msg += "\n";
mmOutputStream.write(msg.getBytes());
// tell the user data were sent
myLabel.setText("Data Sent");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Close the connection to bluetooth printer.
*/
void closeBT() throws IOException {
try {
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I added code to run closeBT function at the end of the sendData function. if you don't close the connection, I think it is hanging in the process of sending.
void sendData() throws IOException {
try {
// the text typed by the user
String msg = myTextbox.getText().toString();
msg += "\n";
mmOutputStream.write(msg.getBytes());
// tell the user data were sent
myLabel.setText("Data Sent");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

Unable to read input from a bluetoothsocket

I've finally managed to connect from my android phone to my device, put I have a problem when I try to read from my bluetooth socket.
So here is my code for establishing connecting to my device, its a class that extends AsyncTask
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
public class Connect extends AsyncTask<String, Void, String> {
private final static String TAG = "+++CONNECT THREAD+++";
ProgressDialog progressDialog;
Context context;
BluetoothSocket tmp;
BluetoothDevice device;
BluetoothAdapter ba;
Button connect;
int bt_port_to_connect;
ReadInput ri;
InputStream is;
byte[] test;
public Connect(Context context, BluetoothDevice device, BluetoothAdapter ba, Button connect) {
this.ba = ba;
this.context = context;
this.device = device;
this.connect = connect;
bt_port_to_connect = 9;
}
protected void onPreExecute() {
progressDialog=ProgressDialog.show(context,"Please Wait..","Connecting to device",false);
}
#Override
protected String doInBackground(String... arg0) {
Method m = null;
try {
m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
}
try {
tmp = (BluetoothSocket) m.invoke(device, bt_port_to_connect);
} 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();
}
try {
ba.cancelDiscovery();
tmp.connect();
ri = new ReadInput(tmp);
ri.start();
} catch (IOException e) {
Log.e("+++CONNECT1+++","EXCEPTION: " + e.getMessage());
try {
tmp.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() " + " insecure socket type" +
" socket during connection failure", e2);
}
Log.e("+++CONNECT2+++", e.getLocalizedMessage());
}
boolean isConnected = tmp.isConnected();
if(isConnected) {
return "connected";
}
else {
return "notConnected";
}
}
protected void onPostExecute(String result) {
progressDialog.dismiss();
if(result.equals("connected")) {
connect.setEnabled(false);
Toast.makeText(context, "Connected to device: "+device.getName().toString(), Toast.LENGTH_LONG).show();
//new ReadIn(context, tmp).execute("");
}
else if(result.equals("notConnected")) {
Toast.makeText(context, "Can`t reach host", Toast.LENGTH_LONG).show();
}
}
}
As you can see, the line below tmp.connect(); I create a new object of a new class, this is the class which I want to handle the reading of the inputStream So here is the code for that class:
import java.io.IOException;
import java.io.InputStream;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
public class ReadInput extends Thread {
BluetoothSocket socket;
private InputStream is;
public ReadInput(BluetoothSocket socket) {
Log.i("READINPUT", "INSIDE READ INPUT THREAD CONSTRUCTOR!!!");
InputStream tmpIn = null;
this.socket = socket;
is = null;
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
Log.e("READINPUT", "Temp socket in created: " + e.getMessage());
}
is = tmpIn;
}
public void run() {
Log.i("READINPUT", "INSIDE READ INPUT THREAD RUN METHOD!!!");
byte[] buffer = new byte[1024];
int bytes = 0;
while(true) {
try {
bytes = is.read(buffer);
} catch (IOException e) {
Log.e("FROM RUN METHOD: ", e.getMessage());
}
Log.i("INPUTSTREAM GOT: ", Integer.toString(bytes));
}
}
}
I have two Log.i methods in my last code, this outputs the correct info to LogCat stating where in the code I am. But it doesnt output the content of the stream to LogCat. What am I doing wrong here? Yes, I've looked into the BluetoothChat example.
Thanks in advance!
EDIT 1
I've done some research in the constructor of the ReadInput Class.
is = tmpIn;
try {
Log.i("InputStream: ", Integer.toString(is.available()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This snippet will only output to logcat that is returns 0 which means that the InputStream is not available. Any suggestions?
I found using a buffered reader works well with a blietooth device. And then I just used a while.loop with br.isReady in a while true listener. Basically makes a "listener"

Android Bluetooth reading btrs232 adapter

I am writing a simple communication program between Android device 2.2 and Bluetooth RS232 adapter.
I managed to connect and send text successfully, but when reading from the adapter the application crashes.
I do appreciate any help and advice.
Thanks
main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="#+id/text_messages"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<Button android:text="Button" android:id="#+id/button_listen"
android:layout_width="wrap_content" android:layout_height="wrap_content">
</Button>
</LinearLayout>
MyActivity.java
package com.epostech.bt232test;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import java.util.Vector;
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.widget.ArrayAdapter;
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 MyActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 3;
private String mac = "";
private static final UUID MY_UUID_INSECURE = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothSocket clientSocket;
// private ArrayAdapter<String> mArrayAdapter;
private Vector<String> deviceMacs = new Vector<String>();
private Vector<String> deviceNames = new Vector<String>();
#SuppressWarnings("unused")
private Handler handler = new Handler();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final TextView messageText = (TextView) findViewById(R.id.text_messages);
// messageText.setVisibility(View.VISIBLE);
setContentView(R.layout.main);
Button listenButton = (Button) findViewById(R.id.button_listen);
listenButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// closeSocket();
sendMessage(clientSocket, "P\r\n");
// testing(mac);
}
});
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
String toastText = "";
/*
* if(bluetooth.isEnabled()){ String address= bluetooth.getAddress();
* String name=bluetooth.getName(); toastText=name+" : "+address;
*
* } else
*/
if (!bluetooth.isEnabled()) {
toastText = "Bluetooth is not Enabled!";
Toast.makeText(this, toastText, Toast.LENGTH_LONG).show();
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
Toast.makeText(this, "BlueTooth Enabled", Toast.LENGTH_LONG).show();
}
Set<BluetoothDevice> pairedDevices = bluetooth.getBondedDevices();
// Toast.makeText(this,"Size="+pairedDevices.size(),
// Toast.LENGTH_LONG).show();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a
// ListView
deviceMacs.add(device.getAddress());
deviceNames.add(device.getName());
}
} else {
Toast.makeText(this, "Size=" + pairedDevices.size(),
Toast.LENGTH_LONG).show();
}
mac = deviceMacs.get(deviceNames.indexOf("M7705B0125"));
BluetoothDevice device = bluetooth.getRemoteDevice(mac);
try {
clientSocket = device
.createRfcommSocketToServiceRecord(MY_UUID_INSECURE);
clientSocket.connect();
// TODO Transfer data using the Bluetooth Socket
} catch (IOException e) {
Log.d("BLUETOOTH", e.getMessage());
}
BluetoothSocketListener bsl = new BluetoothSocketListener(clientSocket, handler, messageText);
Thread messageListener = new Thread(bsl);
messageListener.start();
}
private void closeSocket() {
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void sendMessage(BluetoothSocket socket, String msg) {
OutputStream outStream;
try {
outStream = socket.getOutputStream();
byte[] byteString = msg.getBytes();
byteString[byteString.length - 1] = 0;
outStream.write(byteString);
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
// The Handler that gets information back from the BluetoothChatService
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeSocket();
}
}
BluetoothSocketListener.java
package com.epostech.bt232test;
import java.io.IOException;
import java.io.InputStream;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
public class BluetoothSocketListener implements Runnable {
private BluetoothSocket socket;
private TextView textView;
private Handler handler;
public BluetoothSocketListener(BluetoothSocket socket,
Handler handler, TextView textView) {
this.socket = socket;
this.textView = textView;
this.handler = handler;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
InputStream instream=null;
try {
instream = socket.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String message = "";
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = instream.read(buffer);
message = message + new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity
handler.post(new MessagePoster(textView, message));
} catch (IOException e) {
break;
}
}
}
/*
public void run() {
int bufferSize = 256;
byte[] buffer = new byte[bufferSize];
try {
InputStream instream = socket.getInputStream();
int bytesRead = -1;
String message = "";
while (true) {
message = "";
bytesRead = instream.read(buffer);
if (bytesRead != -1) {
while ((bytesRead==bufferSize)&&(buffer[bufferSize-1] != 0)) {
message = message + new String(buffer, 0, bytesRead);
bytesRead = instream.read(buffer);
}
message = message + new String(buffer, 0, bytesRead - 1);
handler.post(new MessagePoster(textView, message));
//socket.getInputStream();
}
}
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
*/
}
MessagePoster.java
package com.epostech.bt232test;
import android.widget.TextView;
public class MessagePoster implements Runnable {
private TextView textView;
private String message;
public MessagePoster(TextView textView, String message) {
this.textView = textView;
this.message = message;
}
public void run() {
textView.setText(message);
}
}
Problem solved
I can read and write to RS232 and display the result on TextView using Handler to communicate with UI and Socket thread.
It was hard excersise but I did it with simple program as follows:
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// messageText.setVisibility(View.VISIBLE);
setContentView(R.layout.main);
messageText = (TextView) findViewById(R.id.text_messages);
Button listenButton = (Button) findViewById(R.id.button_listen);
listenButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// closeSocket();
sendData(clientSocket, "P\r\n");
}
});
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
String toastText = "";
/*
* if(bluetooth.isEnabled()){ String address= bluetooth.getAddress();
* String name=bluetooth.getName(); toastText=name+" : "+address;
*
* } else
*/
if (!bluetooth.isEnabled()) {
toastText = "Bluetooth is not Enabled!";
Toast.makeText(this, toastText, Toast.LENGTH_LONG).show();
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
Toast.makeText(this, "BlueTooth Enabled", Toast.LENGTH_LONG).show();
}
Set<BluetoothDevice> pairedDevices = bluetooth.getBondedDevices();
// Toast.makeText(this,"Size="+pairedDevices.size(),
// Toast.LENGTH_LONG).show();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a
// ListView
deviceMacs.add(device.getAddress());
deviceNames.add(device.getName());
}
} else {
Toast.makeText(this, "Size=" + pairedDevices.size(),
Toast.LENGTH_LONG).show();
}
mac = deviceMacs.get(deviceNames.indexOf("M7705B0125"));
BluetoothDevice device = bluetooth.getRemoteDevice(mac);
try {
clientSocket = device
.createRfcommSocketToServiceRecord(MY_UUID_INSECURE);
clientSocket.connect();
// TODO Transfer data using the Bluetooth Socket
} catch (IOException e) {
Log.d("BLUETOOTH", e.getMessage());
}
BluetoothSocketListener bsl = new BluetoothSocketListener(clientSocket,
handler, messageText);
Thread messageListener = new Thread(bsl);
messageListener.start();
}// end of onCreate()code
// The Handler that gets information back from the BluetoothChatService
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
messageText.setText(readMessage);
}
};
private void closeSocket() {
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// The Handler that gets information back from the BluetoothChatService
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeSocket();
}
private class BluetoothSocketListener implements Runnable {
private BluetoothSocket socket;
private TextView textView;
private Handler handler;
private InputStream inStream;
private OutputStream outStream;
public BluetoothSocketListener(BluetoothSocket socket, Handler handler,
TextView textView) {
this.socket = socket;
this.textView = textView;
this.handler = handler;
try {
outStream = socket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int data;
try {
inStream = socket.getInputStream();
int bytesRead = -1;
String message = "";
// Keep listening to the InputStream while connected
int len= 0;
while (true) {
try {
// Read from the InputStream
bytesRead = inStream.read(buffer);
message= message+new String(buffer,0,bytesRead);
// Send the obtained bytes to the UI Activity
byte[] byteString = message .getBytes();
byteString[byteString.length - 1] = 0;
outStream.write(byteString);
handler.post(new MessagePoster(textView,"Text="+ message+" "+"Bytes read="+bytesRead));
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
break;
}
}
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
}
private class MessagePoster implements Runnable {
private TextView textView;
private String message;
public MessagePoster(TextView textView, String message) {
this.textView = textView;
this.message = message;
}
public void run() {
textView.setText(message);
}
}
private void sendData(BluetoothSocket socket, String msg) {
OutputStream outStream;
try {
outStream = socket.getOutputStream();
byte[] byteString = msg.getBytes();
//byteString[byteString.length - 1] = 0;
outStream.write(byteString);
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
}
Dont forget to add the permission to the manifest
<uses-permission
android:name="android.permission.BLUETOOTH" />
I discovered one thing using a serial to BT adapter hooked to a microcontroler.
Often, the data sent to the serial port is a string ended by [].
I used a serial to bluetooth adapter ine one of my projects, sending data lines ended by a and found that handling data with a Scanner rather than a standard buffer really works better.
Example of the Bluetooth Chat modified:
Scanner scan = new Scanner(new InputStreamReader(mmInStream));
String line;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
//Send the obtained bytes to the UI Activity
line = scan.next();
mHandler.obtainMessage(CalibrationS2PActivity.MESSAGE_READ, line.length(), -1, line).sendToTarget();
} catch (Exception e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}

Categories

Resources