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;
}
}
Related
static class BluetoothInHandler extends Handler {
private final WeakReference<Bluetooth_dataDisplay> mActivity;
BluetoothInHandler(Bluetooth_dataDisplay activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
final Bluetooth_dataDisplay thizz = mActivity.get();
if (thizz == null) return;
if (msg.what == thizz.handlerState) {
String readMessage = (String) msg.obj;
thizz.myLabel.setText(readMessage);
}
}//end of handle message
}//end of Bluetoothin handler
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth_datadisplay);
myLabel = (TextView)findViewById(R.id.label);
mMyHandler = new BluetoothInHandler(this);
}//end oncreate
#Override
public void onResume() {
super.onResume();
String MAC = getIntent().getStringExtra("MAC");
mAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice bluetoothDevice = mAdapter.getRemoteDevice(MAC);
ConnectingThread t = new ConnectingThread(bluetoothDevice);
t.start();
}
//Setting Up a Connecting Client
private class ConnectingThread extends Thread {
OutputStream mmOutputStream;
InputStream mmInputStream;
StringBuilder recDataString = new StringBuilder();
// private final BluetoothSocket bluetoothSocket;
private final BluetoothDevice bluetoothDevice;
final Handler handler = new Handler();
public ConnectingThread(BluetoothDevice device) {
BluetoothSocket temp = null;
bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket = temp;
}
public void run() {
// Cancel any discovery as it will slow down the connection
mAdapter.cancelDiscovery();
try {
// This will block until it succeeds in connecting to the device
// through the bluetoothSocket or throws an exception
bluetoothSocket.connect();
Log.e("bluetooth socket",".connect");
mmOutputStream = bluetoothSocket.getOutputStream();
mmInputStream = bluetoothSocket.getInputStream();
//beginListenForData();
Bluetooth_dataDisplay.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(Bluetooth_dataDisplay.this, "Connected with Device!", Toast.LENGTH_SHORT).show();
}
});
handler.post(new Runnable() {
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInputStream.read(buffer);
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
mMyHandler.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
});
//beginListenForData();
//Log.e("begin", "begindata");
} catch (IOException connectException) {
connectException.printStackTrace();
try {
bluetoothSocket.close();
Log.e("click6", "blueclose");
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
}
Trying to send data from thread back to UI activity but my app just stuck. :( I don't know what wrong with it. Please help. No error and no crashes of app. I had tried runnableUIthread as well. It didn't work too. So I don't know what to do now.
static class BluetoothInHandler extends Handler {
private final WeakReference<Bluetooth_dataDisplay> mActivity;
BluetoothInHandler(Bluetooth_dataDisplay activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
//change 3
Log.e("test","handleMessage");
final Bluetooth_dataDisplay thizz = mActivity.get();
if (thizz == null) return;
if (msg.what == thizz.handlerState) {
String readMessage = (String) msg.obj;
thizz.myLabel.setText(readMessage);
}
}//end of handle message
}//end of Bluetoothin handler
#Override
public void onResume() {
super.onResume();
String MAC = getIntent().getStringExtra("MAC");
mAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice bluetoothDevice = mAdapter.getRemoteDevice(MAC);
ConnectingThread t = new ConnectingThread(bluetoothDevice,mMyHandler );
t.start();
}
//Setting Up a Connecting Client
private class ConnectingThread extends Thread {
OutputStream mmOutputStream;
InputStream mmInputStream;
StringBuilder recDataString = new StringBuilder();
// private final BluetoothSocket bluetoothSocket;
private final BluetoothDevice bluetoothDevice;
Handler handler;
public ConnectingThread(BluetoothDevice device,Handler mHandler) {
handler = mHandler
BluetoothSocket temp = null;
bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket = temp;
}
public void run() {
// Cancel any discovery as it will slow down the connection
mAdapter.cancelDiscovery();
try {
// This will block until it succeeds in connecting to the device
// through the bluetoothSocket or throws an exception
bluetoothSocket.connect();
Log.e("bluetooth socket",".connect");
mmOutputStream = bluetoothSocket.getOutputStream();
mmInputStream = bluetoothSocket.getInputStream();
//beginListenForData();
Bluetooth_dataDisplay.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(Bluetooth_dataDisplay.this, "Connected with Device!", Toast.LENGTH_SHORT).show();
}
});
//change 7
//handler.post(
new Runnable() {
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// Keep looping to listen for received messages
while (true) {
//change 1
try{
Thread.sleep(1000);
}catch(Throwable e){
e.printStackTrace();
}
try {
bytes = mmInputStream.read(buffer);
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
//change 4;
handler.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
//change 6
Log.e("test","6")
//change 2
e.printStackTrace();
break;
}catch(Throwable e1){
//change 5;
Log.e("test","5")
}
}
}.run();
//});
//beginListenForData();
//Log.e("begin", "begindata");
} catch (IOException connectException) {
connectException.printStackTrace();
try {
bluetoothSocket.close();
Log.e("click6", "blueclose");
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
}
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.
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
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();
}
}
I want to created simple Android bluetooth Client-Server program
Server Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.textView1);
tv2=(TextView)findViewById(R.id.textView2);
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
try {
mBluetoothServerSocket=mBluetoothAdapter.listenUsingRfcommWithServiceRecord(name,uUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket=mBluetoothServerSocket.accept();
mInputStream=mBluetoothSocket.getInputStream();
//if(mInputStream.available()>0){
mBufferedReader=new BufferedReader(new InputStreamReader(mInputStream));
data = mBufferedReader.readLine();
tv1.setText(data);
//}
if(mInputStream.available()>0){
data=mBufferedReader.readLine();
tv2.setText(data);
x++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Client Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lb=(Button)findViewById(R.id.button1);
btAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = btAdapter.getRemoteDevice(addressHTC);
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btAdapter.cancelDiscovery();
btSocket.connect();
String message = "Hello.............. from....... Android......\n";
outStream = btSocket.getOutputStream();
byte[] msgBuffer = message.getBytes();
outStream.write(msgBuffer);
}
catch(IOException e){
e.printStackTrace();
}
lb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String m1="msg 2";
byte[] msgBuffer = m1.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
This application work in one side mode, just Send message to server and show received buffer, But i need to Send back some messages from server to client continuously.
How to do it?
if you have any idea. please share it.
This is works for me for contineously reading. Try it.
try {
BufferedReader Reader = new BufferedReader(
new InputStreamReader(mmSocket.getInputStream()));
while(true)
{
String receivedMsg;
while((receivedMsg = Reader.readLine()) != null)
{
// what you do with your message
}
}
} catch (Exception ex) {
System.out.println(ex);
}
you should have a different thread for listening which will send the message to the activity, this thread can be also the thread sending messages.
that way your the UI wont get stuck and you could receive messages continuously.
an example of such thread:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.util.Log;
public class MessageManager extends Thread {
private static final String TAG = "MessageListener thread";
private BluetoothSocket btConnectedSocket;
private InputStream inStream;
private OutputStream outStream;
private Activity parent;
private boolean run = true;
public MessageManager(BluetoothSocket btConnectedSocket, Activity parent) throws IOException {
this.btConnectedSocket = btConnectedSocket;
this.parent = parent;
inStream = btConnectedSocket.getInputStream();
outStream = btConnectedSocket.getOutputStream();
}
/* this method will listen continuously to messages received through the BT socket until you call cancel
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (run) {
try {
bytes = inStream.read(buffer);
}
catch(IOException ex) {
Log.e(TAG, "error while reading from bt socket");
}
parent.doStuffWithTheMessage(buffer); // pay attention: its in bytes. u need to convert it to a string
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) throws IOException{
outStream.write(bytes);
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
run = false;
try {
btConnectedSocket.close();
} catch (IOException e) { }
}
}