Programmatically connecting two Android devices through Bluetooth - android

I'm trying to get data from one of my devices to another, through bluetooth.
I previously tried to run the bluetoothChat sample code from the android website but have had no success.
I have now moved on to this bit of code that I have found and though it does compile on my devices they don't connect with one another.
Anyone see anything wrong with this code below? And if anyone might know of some good resources for bluetooth on the android I would be appreciative if they would share them with me!
package com.example.bluetooth;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemClickListener {
ArrayAdapter<String> listAdapter;
ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
IntentFilter filter;
BroadcastReceiver receiver;
String tag = "debugging";
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
Log.i(tag, "in handler");
super.handleMessage(msg);
switch(msg.what){
case SUCCESS_CONNECT:
// DO something
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(), "CONNECT", Toast.LENGTH_SHORT).show();
String s = "successfully connected";
connectedThread.write(s.getBytes());
Log.i(tag, "connected");
break;
case MESSAGE_READ:
byte[] readBuf = (byte[])msg.obj;
String string = new String(readBuf);
Toast.makeText(getApplicationContext(), string, 0).show();
break;
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
if(btAdapter==null){
Toast.makeText(getApplicationContext(), "No bluetooth detected", 0).show();
finish();
}
else{
if(!btAdapter.isEnabled()){
turnOnBT();
}
getPairedDevices();
startDiscovery();//
}
}
public void resumeDiscovery(View view){
btAdapter.cancelDiscovery();
btAdapter.startDiscovery();
}
private void startDiscovery() {
// TODO Auto-generated method stub
btAdapter.cancelDiscovery();
btAdapter.startDiscovery();
}
private void turnOnBT() {
// TODO Auto-generated method stub
Intent intent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1);
}
private void getPairedDevices() {
// TODO Auto-generated method stub
devicesArray = btAdapter.getBondedDevices();
if(devicesArray.size()>0){
for(BluetoothDevice device:devicesArray){
pairedDevices.add(device.getName());
}
}
}
private void init() {
// TODO Auto-generated method stub
listView=(ListView)findViewById(R.id.listView);
listView.setOnItemClickListener(this);
listAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
listView.setAdapter(listAdapter);
btAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDevices = new ArrayList<String>();
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
devices = new ArrayList<BluetoothDevice>();
receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
String s = "";
for(int a = 0; a < pairedDevices.size(); a++){
if(device.getName().equals(pairedDevices.get(a))){
//append
s = "(Paired)";
break;
}
}
listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());
}
else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
// run some code
}
else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
// run some code
}
else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
if(btAdapter.getState() == btAdapter.STATE_OFF){
turnOnBT();
}
}
}
};
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(receiver, filter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(receiver);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
finish();
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
BluetoothDevice selectedDevice = devices.get(arg2);
if(btAdapter.isDiscovering()){
btAdapter.cancelDiscovery();
}
if(listAdapter.getItem(arg2).contains("Paired")){
ConnectThread connect = new ConnectThread(selectedDevice);
connect.start();
Log.i(tag, "in click listener");
}
else{
Toast.makeText(getApplicationContext(), "pairing", 0).show();
//pair device
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
Log.i(tag, "construct");
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.i(tag, "get socket failed");
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
btAdapter.cancelDiscovery();
Log.i(tag, "connect - run");
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
Log.i(tag, "connect - succeeded");
} catch (IOException connectException) { Log.i(tag, "connect failed");
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}

The problem is in your init() method which registers the BroadcastReceiver with this activity in your onCreate() method and in onPause() you have unregistered the BroadcastReceiver.
Try to register it in your onResume() method so that you can receive
the broadcast whenever you resume to this activity.

Related

Why isn't my bluetooth activity able to connect to the device I tap on?

I followed a Bluetooth tutorial video on how to create a connection using my app with other Bluetooth devices.
However, I am unable to connect to the devices directly on the app itself. I was expecting the code to allow me to do something like "Connecting..." once I tap on the device name I want to engage a connection with.
Below is my Bluetooth code:
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.internal.widget.AdapterViewCompat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
//import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class Bluetooth extends Activity implements AdapterView.OnItemClickListener {
ArrayAdapter<String> listAdapterBt;
ListView listViewBt;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
IntentFilter filter;
BroadcastReceiver receiver;
//String tag = "debugging";
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg){
super.handleMessage(msg);
switch(msg.what){
case SUCCESS_CONNECT:
//do something
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(), "CONNECT", Toast.LENGTH_SHORT).show();
String s = "successfully connected";
connectedThread.write(s.getBytes());
break;
case MESSAGE_READ:
byte[] readBuf = (byte[])msg.obj;
String string = new String(readBuf);
Toast.makeText(getApplicationContext(), "CONNECT", Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
init(); //initiate Bluetooth
if (btAdapter == null){
Toast.makeText(getApplicationContext(), "No bluetooth detected",Toast.LENGTH_SHORT).show();
finish();
}
else{
if (!btAdapter.isEnabled()){
turnOnBT();
}
getPairedDevices();
startDiscovery();
}
}
private void startDiscovery() {
btAdapter.cancelDiscovery();
btAdapter.startDiscovery();
}
private void turnOnBT() {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1);
}
private void getPairedDevices() {
devicesArray = btAdapter.getBondedDevices();
if (devicesArray.size() > 0){
//add devices in array to list array
for(BluetoothDevice device:devicesArray){
pairedDevices.add(device.getName());
}
}
}
private void init() {
listViewBt = (ListView)findViewById(R.id.listViewBt);
listViewBt.setOnItemClickListener(this);
listAdapterBt = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
listViewBt.setAdapter(listAdapterBt);
btAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDevices = new ArrayList<String>();
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
devices = new ArrayList<BluetoothDevice>();
receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
String s = "";
for (int a = 0; a < pairedDevices.size(); a++) {
if (device.getName().equals(pairedDevices.get(a))) {
//append
s = "Paired";
break;
}
}
// matt-hp (paired)
listAdapterBt.add(device.getName()+" ("+s+") "+"\n"+device.getAddress());
}
else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
//run some code
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
//run some code
}
else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
if (btAdapter.getState() == btAdapter.STATE_OFF){
turnOnBT();
}
}
}
};
registerReceiver(receiver, filter);
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(receiver, filter);
}
#Override
protected void onPause(){
super.onPause();
unregisterReceiver(receiver);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
finish();
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(btAdapter.isDiscovering()){
btAdapter.cancelDiscovery();
}
if (listAdapterBt.getItem(position).contains("Paired")){
BluetoothDevice selectedDevice = devices.get(position);
ConnectThread connect = new ConnectThread(selectedDevice);
connect.start();
Toast.makeText(getApplicationContext(), "device is paired", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "device is not paired", Toast.LENGTH_SHORT).show();
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
btAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
Below is my bluetooth.xml code:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.mdpgrp10.androidmobilecontrollermodule.Bluetooth">
<item android:id="#+id/action_settings" android:title="#string/action_settings"
android:orderInCategory="100" app:showAsAction="never" />
</menu>
Just hoping for any help in any way. Much appreciated!

send and receive string with bluetooth in 2 android devices

hi guys i am trying to send string from one phone to anther .
1) from one phone(client) i am clicking the paired listview to connect with the anther device(ConnectThread).
2) the second phone which is the server alerts that he has been connected with the device in step 1(AcceptThread).
3) after he get connected he start a new managerconnection thread and send along a string(in AcceptThread after connecting is sucessfull it starts a new managerConnection thread .
4) the other phone(after been connected to server it starts a new managerConnecting thread) should get the bytes from function read and put in the log how much bytes he read it seems its not getting any bytes at all can someone tell me what should i changed in my code?
package com.example.barhom.waves;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class BlueToothServerActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
private static final String TAG = "buckysmessage";
private Button onBtn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private TextView serverStatus;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private AcceptThread mSecureAcceptThread;
private manageConnectedSocket manager ;
// Unique UUID for this application
private static final UUID MY_UUID =
UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final String NAME_SECURE = "waves";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth_server);
serverStatus = (TextView) findViewById(R.id.serverStatus);
// take an instance of BluetoothAdapter - Bluetooth radio
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
onBtn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
text = (TextView) findViewById(R.id.text);
onBtn = (Button)findViewById(R.id.turnOn);
onBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button)findViewById(R.id.turnOff);
offBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button)findViewById(R.id.paired);
listBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String value = (String)adapter.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),"Listview clicked" ,
Toast.LENGTH_LONG).show();
// assuming string and if you want to get the value on click of list item
// do what you intend to do on click of listview row
}
});
}
}
#Override
protected void onResume() {
super.onResume();
// setting the device to listen for connections(bluetooth)
AcceptThread mSecureAcceptThread= new AcceptThread();
mSecureAcceptThread.start();
}
public void on(View view){
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(),"Bluetooth turned on" ,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
if(myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view){
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast.makeText(getApplicationContext(),"Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view){
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(),"Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
private boolean running = true;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
serverStatus.setText("Server Status: Listing for connection");
Log.d(TAG, "SERVER IS LISING FOR CONNECTIONS");
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = myBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID);
} catch (IOException e) {running = false; }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (running) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
manager=new manageConnectedSocket(socket);
manager.start();
try {
mmServerSocket.close();
Log.d(TAG, "SERVER IS CONNECTED");
String blahblah="asdasds";
manager.write(blahblah.getBytes());
break;
}catch (IOException e) {
break;
}
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
private class manageConnectedSocket extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public manageConnectedSocket(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) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
} 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);
Log.d(TAG,"WROTE A STRING TO ANTHER PHONE");
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
and the code for the client(the second phone):
package com.example.barhom.waves;
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.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class BlueToothClientActivity extends AppCompatActivity {
private static final int REQUEST_ENABLE_BT = 1;
private static final String TAG = "buckysmessage";
private Button onBtn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private TextView serverStatus;
private ConnectThread mConnectThread;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private manageConnectedSocket manager ;
// Unique UUID for this application
private static final UUID MY_UUID =
UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final String NAME_SECURE = "waves";
private BluetoothDevice device;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth_client);
serverStatus = (TextView) findViewById(R.id.serverStatus);
// take an instance of BluetoothAdapter - Bluetooth radio
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
onBtn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(), "Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
text = (TextView) findViewById(R.id.text);
onBtn = (Button)findViewById(R.id.turnOn);
onBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button)findViewById(R.id.turnOff);
offBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button)findViewById(R.id.paired);
listBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
Toast.makeText(getApplicationContext(),"adress is"+address,
Toast.LENGTH_LONG).show();
device = myBluetoothAdapter.getRemoteDevice(address);
ConnectThread mConnectThread=new ConnectThread(device );
mConnectThread.start();
// assuming string and if you want to get the value on click of list item
// do what you intend to do on click of listview row
}
});
}
}
#Override
protected void onResume() {
super.onResume();
}
public void on(View view){
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(),"Bluetooth turned on" ,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
if(myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view){
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast.makeText(getApplicationContext(),"Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view){
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(), "Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
myBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
manager=new manageConnectedSocket(mmSocket);
manager.start();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
// manageConnectedSocket(mmSocket);
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class manageConnectedSocket extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public manageConnectedSocket(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
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
int read = -1;
final byte[] bytes = new byte[2048];
for (; (read = mmInStream.read(bytes)) > -1;) {
final int count = read;
Log.d(TAG,"String size is"+count);
}
} 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) { }
}
}
}
any help will be great!
thanks.

send and receive data via bluetooth

you can say that i'm new in android development, i need some help to synchronize some data in two devices with my application, i have done all necessary things like searching for available devices and pairing and unpairing ... all what i need now is how to make a connection between the two devices and send and receive data, to explain more, i need to select a device from my listview and connect with it, after that lets say that i have a text field and a textview and a button, when i click on the button i need to send the text in the textfield of the first device to the textview of other device and vise-versa.
here is all my code :
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
private Button onBtn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ArrayList<BluetoothDevice> devices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private String tag = "debugging";
protected static final UUID MY_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
Log.i(tag, "in handler");
super.handleMessage(msg);
switch (msg.what) {
case SUCCESS_CONNECT:
// DO something
ConnectedThread connectedThread = new ConnectedThread(
(BluetoothSocket) msg.obj);
Toast.makeText(getApplicationContext(), "CONNECT", 0).show();
String s = "successfully connected";
connectedThread.write(s.getBytes());
Log.i(tag, "connected");
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String string = new String(readBuf);
Toast.makeText(getApplicationContext(), string, 0).show();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// take an instance of BluetoothAdapter - Bluetooth radio
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (myBluetoothAdapter == null) {
onBtn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(),
"Your device does not support Bluetooth", Toast.LENGTH_LONG)
.show();
} else {
myListView = (ListView) findViewById(R.id.listView1);
BTArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
devices = new ArrayList<BluetoothDevice>();
myListView.setAdapter(BTArrayAdapter);
text = (TextView) findViewById(R.id.text);
onBtn = (Button) findViewById(R.id.turnOn);
onBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
on(v);
}
});
offBtn = (Button) findViewById(R.id.turnOff);
offBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
off(v);
}
});
listBtn = (Button) findViewById(R.id.paired);
listBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
list(v);
}
});
findBtn = (Button) findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
find(v);
}
});
// create the arrayAdapter that contains the BTDevices, and set it
// to the ListView
myListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (myBluetoothAdapter.isDiscovering()) {
myBluetoothAdapter.cancelDiscovery();
}
BluetoothDevice selectedDevice = devices.get(position);
if (pairedDevices.contains(selectedDevice)) {
if (unpairDevice(selectedDevice))
Toast.makeText(getApplicationContext(),
"Device unpaired", Toast.LENGTH_LONG)
.show();
else
Toast.makeText(getApplicationContext(),
"Problem while unpairing device",
Toast.LENGTH_LONG).show();
} else {
if (pairDevice(selectedDevice)) {
Toast.makeText(getApplicationContext(),
"Device paired", Toast.LENGTH_LONG).show();
ConnectThread connect = new ConnectThread(
selectedDevice);
connect.start();
} else
Toast.makeText(getApplicationContext(),
"Problem while pairing device",
Toast.LENGTH_LONG).show();
}
}
});
}
}
// For Pairing
private boolean pairDevice(BluetoothDevice device) {
try {
Log.d("pairDevice()", "Start Pairing...");
Method m = device.getClass()
.getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
return true;
} catch (Exception e) {
return false;
}
}
// For UnPairing
private boolean unpairDevice(BluetoothDevice device) {
try {
Log.d("unpairDevice()", "Start Un-Pairing...");
Method m = device.getClass()
.getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
return true;
} catch (Exception e) {
return false;
}
}
public void on(View view) {
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(), "Bluetooth turned on",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view) {
BTArrayAdapter.clear();
// get paired devices
// pairedDevices.clear();
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for (BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
Toast.makeText(getApplicationContext(), "Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the
// arrayAdapter
devices.add(device);
BTArrayAdapter.add(device.getName() + "\n"
+ device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
Toast.makeText(getApplicationContext(), "Discovery cancelled",
Toast.LENGTH_SHORT).show();
myBluetoothAdapter.cancelDiscovery();
} else {
Toast.makeText(getApplicationContext(), "Discovering new devices",
Toast.LENGTH_SHORT).show();
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(
BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view) {
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(), "Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(bReceiver);
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
Log.i(tag, "construct");
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server
// code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.i(tag, "get socket failed");
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
myBluetoothAdapter.cancelDiscovery();
Log.i(tag, "connect - run");
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
Log.i(tag, "connect - succeeded");
} catch (IOException connectException) {
Log.i(tag, "connect failed");
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) {
}
return;
}
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) {
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
}

How to keep transmitting data in Android Bluetooth connection?

I am developing an android application which transmits queries to a bluetooth device and retrieves data from it. In the app, a connection is established by tapping on an available device in the upper part of the screen, and then there's a button on the bottom half which triggers the sending of the query and the text box next to it displays the data.
I am able to successfully connect to the device and fetch data from it once, but when I hit the query button the second time around, the app crashes.
In the code I start the ConnectedThread thread once I hit the button, and then at the end of the thread code a handler is called which then displays the text on the screen. The second time I hit the button my code tries to start the same thread again - this causes the error. I have been trying out to a way to stop the connectedThread once the received data is received, this way I can start and close the connectedThread for every transmit-receive.
Can you please suggest a solution to the issue or a way to improvise the code structure. Any help will be appreciated.
Thanks
package com.test.bluetooth;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Main_Activity extends Activity implements OnItemClickListener {
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
ArrayAdapter<String> listAdapter;
ListView listView;
Button mConnect;
TextView mResponse;
IntentFilter filter;
BroadcastReceiver receiver;
String tag = "Debug";
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
Log.i(tag, "Handler starts");
super.handleMessage(msg);
switch(msg.what){
case SUCCESS_CONNECT:
final ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(), "Connected", 0).show();
mConnect.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
//Log.v("EditText", mCommand.getText().toString());
//String Command = mCommand.getText().toString();
byte[] inputs = {0x30, 0x31, 0x30, 0x44, 0x0d, 0x0a};
connectedThread.write(inputs);
Log.i(tag, "sent ");
connectedThread.start();
Log.i(tag, "sent 2");
}
});
break;
case MESSAGE_READ:
byte[] TxBuf = (byte[])msg.obj;
String string = new String(TxBuf);
Log.d("ReceiverValue", string);
mResponse.setText(string);
break;
}
}
};
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if(btAdapter.isDiscovering()){
btAdapter.cancelDiscovery();
}
if(listAdapter.getItem(arg2).contains("Paired")){
BluetoothDevice selectedDevice = devices.get(arg2);
ConnectThread connect = new ConnectThread(selectedDevice);
connect.start();
Log.i(tag, "in click listener");
}
else{
Toast.makeText(getApplicationContext(), "device is not paired", 0).show();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
if(btAdapter==null){
Toast.makeText(getApplicationContext(), "No bluetooth detected", 0).show();
finish();
}
else{
if(!btAdapter.isEnabled()){
turnOn();
}
getPairedDevices();
startDiscovery();
}
}
private void startDiscovery() {
// TODO Auto-generated method stub
btAdapter.cancelDiscovery();
btAdapter.startDiscovery();
}
private void turnOn() {
// TODO Auto-generated method stub
Intent intent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1);
}
private void getPairedDevices() {
// TODO Auto-generated method stub
devicesArray = btAdapter.getBondedDevices();
if(devicesArray.size()>0){
for(BluetoothDevice device:devicesArray){
pairedDevices.add(device.getName());
}
}
}
private void init() {
// TODO Auto-generated method stub
listView=(ListView)findViewById(R.id.listView);
mConnect=(Button)findViewById(R.id.bConnectNew);
//mCommand=(EditText)findViewById(R.id.etCommand);
mResponse=(TextView)findViewById(R.id.tvResponse);
listView.setOnItemClickListener(this);
listAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
listView.setAdapter(listAdapter);
btAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDevices = new ArrayList<String>();
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
devices = new ArrayList<BluetoothDevice>();
receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
String s = "";
for(int a = 0; a < pairedDevices.size(); a++){
if(device.getName().equals(pairedDevices.get(a))){
//append
s = "(Paired)";
break;
}
}
listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());
}
else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
}
else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
}
else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
if(btAdapter.getState() == btAdapter.STATE_OFF){
turnOn();
}
}
}
};
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(receiver, filter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(receiver);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
finish();
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
Log.i(tag, "construct");
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.i(tag, "get socket failed");
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
btAdapter.cancelDiscovery();
Log.i(tag, "connect - run");
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
Log.i(tag, "connect - succeeded");
} catch (IOException connectException) { Log.i(tag, "connect failed");
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(Main_Activity.SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(Main_Activity.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) { }
}
}
}
The XML layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Paired Devices"
android:id="#+id/tvPD"
/>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="100dip"
android:layout_above="#+id/Border"
android:layout_below="#+id/tvPD" >
</ListView>
<Button
android:id="#+id/bConnectNew"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/tvResponse"
android:layout_alignBottom="#+id/tvResponse"
android:layout_alignParentLeft="true"
android:layout_marginLeft="45dp"
android:text="Send" />
<TextView
android:id="#+id/tvResponse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="188dp"
android:layout_marginRight="26dp"
android:text="Response displayed here" />
<View
android:id="#+id/Border"
android:layout_width="wrap_content"
android:layout_height="3dip"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_weight="10"
android:background="#android:color/black" />
</RelativeLayout>
enter code here

Displaying Bluetooth Serial Data

I am new to Android development and have been working with Bluetooth communication on my Tablet running 4.2.2. I am looking to receive data sent from a Bluetooth module to my Tablet. I have a good understanding of how to set up Bluetooth sockets via the Android website, however I need help in receiving the incoming serial data. Using the code below, I am able to find the module, open a socket connection and connect to it (as indicated by a green light on the module), however I need help in displaying the transmitted data on the UI via a TextView. The module is sending 2 bytes of data every second at 9600 baud. It is my understanding that run() reads in the 2 bytes of data and stores it in the buffer. Then these bytes get passed to the handler which display it on the screen via "case MESSAGE_READ;". Could someone please let me know what I am doing incorrectly?
package com.example.bluetoothtest;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemClickListener {
TextView mTextView;
ArrayAdapter<String> listAdapter;
ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
IntentFilter filter;
BroadcastReceiver receiver;
String tag = "debugging";
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
Log.i(tag, "in handler");
super.handleMessage(msg);
switch(msg.what){
case SUCCESS_CONNECT:
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(), "CONNECT", 0).show();
String s = "successfully connected";
connectedThread.write(s.getBytes());
Log.i(tag, "connected");
break;
case MESSAGE_READ:
String str = (String)msg.obj;
mTextView.setText(str);
}
super.handleMessage(msg);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView=(TextView)findViewById(R.id.txtData);
init();
if(btAdapter==null){
Toast.makeText(getApplicationContext(), "No bluetooth detected", 0).show();
finish();
}
else{
if(!btAdapter.isEnabled()){
turnOnBT();
}
getPairedDevices();
startDiscovery();
}
}
private void startDiscovery() {
// TODO Auto-generated method stub
btAdapter.cancelDiscovery();
btAdapter.startDiscovery();
}
private void turnOnBT() {
// TODO Auto-generated method stub
Intent intent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1);
}
private void getPairedDevices() {
// TODO Auto-generated method stub
devicesArray = btAdapter.getBondedDevices();
if(devicesArray.size()>0){
for(BluetoothDevice device:devicesArray){
pairedDevices.add(device.getName());
}
}
}
private void init() {
// TODO Auto-generated method stub
listView=(ListView)findViewById(R.id.listView);
listView.setOnItemClickListener(this);
listAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
listView.setAdapter(listAdapter);
btAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDevices = new ArrayList<String>();
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
devices = new ArrayList<BluetoothDevice>();
receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
String s = "";
for(int a = 0; a < pairedDevices.size(); a++){
if(device.getName().equals(pairedDevices.get(a))){
//append
s = "(Paired)";
break;
}
}
listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());
}
else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
}
else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
}
else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
if(btAdapter.getState() == btAdapter.STATE_OFF){
turnOnBT();
}
}
}
};
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(receiver, filter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(receiver);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
finish();
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if(btAdapter.isDiscovering()){
btAdapter.cancelDiscovery();
}
if(listAdapter.getItem(arg2).contains("Paired")){
BluetoothDevice selectedDevice = devices.get(arg2);
ConnectThread connect = new ConnectThread(selectedDevice);
connect.start();
Log.i(tag, "in click listener");
}
else{
Toast.makeText(getApplicationContext(), "device is not paired", 0).show();
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
Log.i(tag, "construct");
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.i(tag, "get socket failed");
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
btAdapter.cancelDiscovery();
Log.i(tag, "connect - run");
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
Log.i(tag, "connect - succeeded");
} catch (IOException connectException) { Log.i(tag, "connect failed");
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
Log.i(tag, "socket connect success");
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
Log.i(tag, "socket success");
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i(tag, "run success");
byte[] buffer = new byte[2];
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
Log.i(tag, "buffer read OK");
// Send the obtained bytes to the UI activity
String str = new String(buffer);
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, str).sendToTarget();
}catch (Exception e) {
Log.i(tag, "buffer read failed");
System.out.print("read error");
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) { }
}
}
}
Try:
case SUCCESS_CONNECT:
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(), "CONNECT", 0).show();
String s = "successfully connected";
connectedThread.write(s.getBytes());
Log.i(tag, "connected");
connectedThread.run();
break;
Actually, you should call connectedThread.start(), NOT connectedThread.run(). The start() method causes connectedThread to do its run() method on a separate thread, If you directly call run(), is suggested above, then only that run() method (which is usally an infinite loop, will block all other code, including the UI thread.

Categories

Resources