I am creating an Android app that allows me to control a device connected to Arduino using Bluetooth, with Android 4.4.2, Arduino Uno and HC-05 Module.
Right now I'm finding serious difficulties to print data in the Arduino serial (in order to verify if it's really working). I tried everything I have found in this or other forums related to this topic.
For the moment, I have been able to detect the devices, pair with them and create the Socket and the OutputStream, but for some reason the data doesn't show up.
The code is 2 basic Activities and their layouts (Android) and the Arduino code:
Image of how it shows the available devices.
Image of how now that device is paired with our Android Device.
GetPaired.java:
Basically gets the available devices, show them in a custom ListView, allows you to pair/unpair with them and after you get the device paired, you go to the ConnectionControl activity.
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
public class GetPaired extends Activity {
ListView listViewPaired;
ListView listViewDetected;
ArrayList<String> arrayListpaired;
Button buttonSearch,buttonControl;
ArrayAdapter<String> adapter, detectedAdapter;
BluetoothDevice bdDevice;
ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
ListItemClickedonPaired listItemClickedonPaired;
BluetoothAdapter bluetoothAdapter = null;
ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
ListItemClicked listItemClicked;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_demo);
listViewDetected = (ListView)
findViewById(R.id.listViewDetected);
listViewPaired = (ListView) findViewById(R.id.listViewPaired);
buttonSearch = (Button) findViewById(R.id.buttonSearch);
buttonControl = (Button) findViewById(R.id.buttonControl);
arrayListpaired = new ArrayList<String>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice();
listItemClickedonPaired = new ListItemClickedonPaired();
arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
adapter = new ArrayAdapter<String>(GetPaired.this,
R.layout.custom_layout, arrayListpaired);
detectedAdapter = new ArrayAdapter<String>(GetPaired.this,
R.layout.custom_layout);
listViewDetected.setAdapter(detectedAdapter);
listItemClicked = new ListItemClicked();
detectedAdapter.notifyDataSetChanged();
listViewPaired.setAdapter(adapter);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
//Get all the paired bluetooth devices with Android.
getPairedDevices();
listViewDetected.setOnItemClickListener(listItemClicked);
listViewPaired.setOnItemClickListener(listItemClickedonPaired);
}
private void getPairedDevices() {
Set<BluetoothDevice> pairedDevice =
bluetoothAdapter.getBondedDevices();
if (pairedDevice.size() > 0) {
for (BluetoothDevice device : pairedDevice) {
arrayListpaired.add(device.getName() + "\n" +
device.getAddress());
arrayListPairedBluetoothDevices.add(device);
break;
}
}
adapter.notifyDataSetChanged();
}
//When clicked a bluetooth device from the available list, a bond is
created between them.
class ListItemClicked implements OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
// TODO Auto-generated method stub
bdDevice = arrayListBluetoothDevices.get(position);
Log.i("Log", "The device : " + bdDevice.toString());
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if (isBonded) {
getPairedDevices();
adapter.notifyDataSetChanged();
Log.i("Log", "The bond is created: " + isBonded);
}
} catch (Exception e) {
e.printStackTrace();
}
connect(bdDevice);
}
}
//When clicked in the list of paired devices, you remove the bond and
the pairing.
class ListItemClickedonPaired implements OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
bdDevice = arrayListPairedBluetoothDevices.get(position);
try {
Boolean removeBonding = removeBond(bdDevice);
if (removeBonding) {
arrayListpaired.remove(position);
adapter.notifyDataSetChanged();
}
Log.i("Log", "Removed" + removeBonding);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private Boolean connect(BluetoothDevice bdDevice) {
Boolean bool = false;
try {
Log.i("Log", "service method is called ");
Class cl = Class.forName("android.bluetooth.BluetoothDevice");
Class[] par = {};
Method method = cl.getMethod("createBond", par);
bool = (Boolean) method.invoke(bdDevice);
} catch (Exception e) {
Log.i("Log", "Inside catch of serviceFromDevice Method");
e.printStackTrace();
}
return bool.booleanValue();
}
public boolean removeBond(BluetoothDevice btDevice)
throws Exception {
Class btClass =
Class.forName("android.bluetooth.BluetoothDevice");
Method removeBondMethod = btClass.getMethod("removeBond");
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
public boolean createBond(BluetoothDevice btDevice)
throws Exception {
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
//Searches for available bluetooth devices to add them to the
Detected
List.
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
Toast.makeText(context, "ACTION_FOUND",
Toast.LENGTH_SHORT).show();
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (arrayListBluetoothDevices.size() < 1) // this checks
if the size of bluetooth device is 0,then add the
{ // device to
the arraylist.
detectedAdapter.add(device.getName() + "\n" +
device.getAddress());
arrayListBluetoothDevices.add(device);
detectedAdapter.notifyDataSetChanged();
} else {
boolean flag = true; // flag to indicate that
particular device is already in the arlist or not
for (byte i = 0; i < arrayListBluetoothDevices.size();
i++) {
if
(device.getAddress().equals(arrayListBluetoothDevices.get(i).getAddress())
) {
flag = false;
}
}
if (flag == true) {
detectedAdapter.add(device.getName() + "\n" +
device.getAddress());
arrayListBluetoothDevices.add(device);
detectedAdapter.notifyDataSetChanged();
}
}
}
}
};
//Method that starts the search of bluetooth devices to connect with.
public void startSearching(View v) {
arrayListBluetoothDevices.clear();
Log.i("Log", "in the start searching method");
IntentFilter intentFilter = new
IntentFilter(BluetoothDevice.ACTION_FOUND);
GetPaired.this.registerReceiver(myReceiver, intentFilter);
bluetoothAdapter.startDiscovery();
}
//When you have the device paired with Android, you can go to the
next
Activity, where the proper connection is stablished.
public void onControl(View v) {
if (arrayListPairedBluetoothDevices.size() > 0) {
Log.i("Log", "There is a paired device.");
Intent sipoptent = new Intent(getApplicationContext(),
ConnectionControl.class).putExtra("Bluetooth",
arrayListPairedBluetoothDevices.get(0));
startActivity(sipoptent);
if (arrayListPairedBluetoothDevices.get(0) != null) {
} else {
}
} else {
Log.i("Log", "Not paired to a device yet.");
Toast.makeText(GetPaired.this, "Not paired to a device
yet.",
Toast.LENGTH_SHORT).show();
}
}
}
The ConnectionControl Activity:
Receives an intent with a BluetoothDevice Object, as the device we are going to connect with. Creates the BluetoothSocket, the connection Thread the OutputStream.
*In this part of the code I tried to get another UUID, but again couldn't find anything.
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import java.util.UUID;
import java.io.OutputStream;
public class ConnectionControl extends AppCompatActivity {
Button on, off;
private BluetoothSocket btSocket = null;
private BluetoothDevice device;
private OutputStream mmOutStream =null;
// SPP UUID service - this should work for most devices
private static final UUID BTMODULEUUID = UUID.fromString("00001101-
0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
on = (Button) findViewById(R.id.onbutton);
off = (Button) findViewById(R.id.offbutton);
device = getIntent().getExtras().getParcelable("Bluetooth");
//Bluetooth device information retrieved by an Intent.
Toast.makeText(ConnectionControl.this, device.getAddress(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onResume() {
super.onResume();
try {
//Creation of the socket of the connection.
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(),"Socket connection failed.",
Toast.LENGTH_LONG).show();
}
// Establish the Bluetooth socket connection.
try {
btSocket.connect();
ConnectedThread(btSocket);
write("x");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {}
}
}
//Creates secure outgoing connecetion with BT device using UUID
private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
throws IOException {
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
}
//Creates the OutputStream from the socket.
public void ConnectedThread(BluetoothSocket socket) {
OutputStream tmpOut = null;
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Connection Not
Established.", Toast.LENGTH_LONG).show();
}
Toast.makeText(getBaseContext(), "Connection Established.", Toast.LENGTH_LONG).show();
mmOutStream = tmpOut;
}
#Override
public void onPause()
{
super.onPause();
try
{
//Don't leave Bluetooth sockets open when leaving activity
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
//Transforms a String input into an array of bytes to send to the bluetooth device.
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Conection failed.", Toast.LENGTH_LONG).show();
}
}
public void onON(View view){
write("0");
}
public void onOFF(View view){
write("1");
}
}
And the Arduino code:
In the Arduino hardware I connected the 5V and already entered in AT mode to the Bluetooth to change its name before.
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// set the data rate for the SoftwareSerial port
mySerial.begin(9600);
}
void loop() { // run over and over
if (mySerial.available()) {
Serial.write(mySerial.read());
}
if (Serial.available()) {
mySerial.write(Serial.read());
}
}
What can I try next?
UPDATE:
If you have to use this code for a project feel free to use it.
I have managed to solve the issue, the Arduino code was the problem, this is the working code:
#include <SoftwareSerial.h>
SoftwareSerial BTserial(11, 10); // RX | TX
char c = ' ';
void setup()
{
Serial.begin(9600);
Serial.println("Arduino is ready");
// HC-05 default serial speed for commincation mode is 9600
BTserial.begin(9600);
}
void loop()
{
if (BTserial.available())
{
c = BTserial.read();
Serial.write(c);
}
// Keep reading from Arduino Serial Monitor and send to HC-05
if (Serial.available())
{
c = Serial.read();
BTserial.write(c);
}
}
Related
I'm trying to make an application that is using bluetooth.It's very simple but I'm stuck at connecting devices.
So far I've made 2 listviews, one is displaying paired devices and the other found devices.I dont understand how sockets work and how to make the device server or a client.
Can someone please explain me that or at least tell me what to do with the code I already made(copied).
I've gone through all the tutorials I could find and I still dont understand it.The bluetooth chat example is very confusing, I'm a beginner in android programming and didn't really study much java.
This is the code:
public class ConnectThread extends Thread{
BluetoothDevice device;
private BluetoothSocket socket;
ConnectThread(){
connect(device, MY_UUID);
}
public boolean connect(BluetoothDevice bTDevice, UUID mUUID) {
BluetoothSocket temp = null;
try {
temp = bTDevice.createRfcommSocketToServiceRecord(mUUID);
} catch (IOException e) {
Log.d("CONNECTTHREAD","Could not create RFCOMM socket:" + e.toString());
return false;
}
try {
socket.connect();
} catch(IOException e) {
Log.d("CONNECTTHREAD","Could not connect: " + e.toString());
try {
socket.close();
} catch(IOException close) {
Log.d("CONNECTTHREAD", "Could not close connection:" + e.toString());
return false;
}
}
return true;
}
public boolean cancel() {
try {
socket.close();
} catch(IOException e) {
Log.d("CONNECTTHREAD","Could not close connection:" + e.toString());
return false;
}
return true;
}
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = bluetooth.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) { }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
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)
try {
mmServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}}
This is the xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight="1"
android:baselineAligned="false">
<ListView
android:layout_width="170dp"
android:layout_height="fill_parent"
android:layout_gravity="start"
android:background="#drawable/lviewbg"
android:id="#+id/paired_devies">
</ListView>
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="fill_horizontal"
android:background="#drawable/lviewbg"
android:id="#+id/new_devices">
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp">
<Button
android:id="#+id/discover"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="#aa0000ff"
android:text="#string/disc"
style="?android:attr/buttonBarButtonStyle"
/>
<Button
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="#aa0000ff"
android:text="#string/discoverable"
android:onClick="makeDiscoverable"
style="?android:attr/buttonBarButtonStyle"
/>
</LinearLayout>
</LinearLayout>
This is rest of the code if you need it:
package com.example.user.broj;
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.support.v7.app.AppCompatActivity;
import android.util.Log;
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.util.Set;
import java.util.UUID;
public class BluetoothDevices extends AppCompatActivity{
private static final String TAG = "DeviceListActivity";
private static final boolean D = true;
BluetoothDevice device;
static int REQUEST_ENABLE_BT = 1;
static int DISCOVERABLE_BT_REQUEST_CODE = 1;
static int DISCOVERABLE_DURATION = 120;
public static String EXTRA_DEVICE_ADDRESS = "device_address";
private BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
//This is used for connecting devices
static final String NAME = "BluetoothGame";
static final UUID MY_UUID = UUID.fromString("ae19c8fa-9b60-11e5-8994-feff819cdc9f");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
Button scanButton = (Button) findViewById(R.id.discover);
scanButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
doDiscovery();
view.setClickable(false);
}
});
//enabling bluetooth
if(!bluetooth.isEnabled()){
Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(btIntent, REQUEST_ENABLE_BT);
}
//arrayadapters for paired and new devices list views
mPairedDevicesArrayAdapter = new ArrayAdapter<>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<>(this, R.layout.device_name);
//listview for paired devices
ListView deviceList = (ListView) findViewById(R.id.paired_devies);
deviceList.setAdapter(mPairedDevicesArrayAdapter);
deviceList.setOnItemClickListener(mDeviceClickListener);
//listview for new devices
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
bluetooth = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetooth.getBondedDevices();
if (pairedDevices.size() > 0) {
//findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(noDevices);
}
}
//button onClick for making the device discoverable
public void makeDiscoverable(View view) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERABLE_DURATION);
startActivityForResult(discoverableIntent, DISCOVERABLE_BT_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DISCOVERABLE_BT_REQUEST_CODE){
if (resultCode == DISCOVERABLE_DURATION){
Toast.makeText(getApplicationContext(), "Your device is now discoverable by other devices for " +
DISCOVERABLE_DURATION + " seconds",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Fail to enable discoverability on your device.",
Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (bluetooth != null) {
bluetooth.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
private void doDiscovery() {
if (D) Log.d(TAG, "doDiscovery()");
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
setTitle(R.string.scanning);
// Turn on sub-title for new devices
// findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
// If we're already discovering, stop it
if (bluetooth.isDiscovering()) {
bluetooth.cancelDiscovery();
}
// Request discover from BluetoothAdapter
bluetooth.startDiscovery();
}
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
bluetooth.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
finish();
}
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Button scanButton = (Button) findViewById(R.id.discover);
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
scanButton.setClickable(true);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
}
Async class for connection via Bluetoothsocket
UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
InputStream is1;
OutputStream os1;
BluetoothAdapter bluetoothAdapter = null;
BluetoothSocket socket = null;
class UserInterface extends Thread {
BluetoothDevice bdDevice;
public UserInterface() {
bdDevice = your pair device;
}
#Override
public void run() {
Looper.prepare();
try {
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(bdDevice.getAddress());
if (socket != null && socket.isConnected()) {
is1.close();
os1.close();
socket.close();
}
try {
socket = device.createInsecureRfcommSocketToServiceRecord(SERIAL_UUID);
} catch (Exception e) {
Log.e("", "Error creating socket");
}
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
try {
socket.connect();
Log.e("", "Connected Rfcomm");
} catch (IOException e) {
Log.e("", e.getMessage());
try {
Log.e("", "trying fallback...");
socket = device.createInsecureRfcommSocketToServiceRecord(SERIAL_UUID);
socket.connect();
Log.e("", "Connected serial UDID");
} catch (Exception e2) {
Log.e("", "Couldn't establish Bluetooth connection!");
}
}
if (socket.isConnected()) {
// dismiss Progress Dialog
os1 = socket.getOutputStream();
is1 = socket.getInputStream();
Log.i("TAG", "Socket Connected");
//code after socket connect
} else {
// dismiss Progress Dialog
showProgressDialogToast("Please restart bluetooth Device");
closeSocket();
Log.i("TAG", "Socket Disconnected");
}
Log.i("Log", "Removed" + bdDevice.getName());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i("Log", "Under Catch of thread");
e.printStackTrace();
// dismiss Progress Dialog
}
}
}
use Thread class like this
UserInterface userInterface = new UserInterface();
userInterface.start();
Basically refer the tutorial given by android developers on their site.
In every connectivity there should be one server and one client. The server will just run the accept thread and the client will run the connect thread. Once the accept thread started, you need to connect from the client side with the proper device name.
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.
package com.ubitech.tokencallingsystem;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
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.util.Log;
import android.view.Menu;
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 android.widget.ToggleButton;
public class BluetoothActivity extends Activity{
private final static UUID uuid = UUID.fromString("38bf8160-61ce-11e5-a837-0800200c9a66");
private BluetoothAdapter bluetoothAdapter;
private ToggleButton toggleBtn;
private Button scanBtn;
private ListView listView;
#SuppressWarnings("rawtypes")
private ArrayAdapter adapter;
private static final int ENABLE_BT_REQUEST_CODE = 1;
#SuppressWarnings("rawtypes")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth_activity);
toggleBtn = (ToggleButton) findViewById(R.id.toggleButton);
scanBtn = (Button) findViewById(R.id.scan);
listView = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemValue = (String) listView.getItemAtPosition(position);
String MAC = itemValue.substring(itemValue.length() - 17);
Toast.makeText(getApplicationContext(), itemValue+"="+MAC, Toast.LENGTH_SHORT).show();
BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(MAC);
// Initiate a connection request in a separate thread
ConnectingThread t = new ConnectingThread(bluetoothDevice);
t.start();
AcceptThread th = new AcceptThread();
th.start();
System.out.println("In itemonclick listner");
}
});
}
public void onToggleClicked(View view){
//adapter.clear();
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(), "Oops! Bluetooth not supported.", Toast.LENGTH_SHORT).show();
} else {
if(toggleBtn.isChecked()){
scanDevices(view);
} else{
Toast.makeText(getApplicationContext(), "Turning off bluetooth..", Toast.LENGTH_SHORT).show();
adapter.clear();
bluetoothAdapter.disable();
}
}
}
public void scanDevices(View view){
adapter.clear();
if(!bluetoothAdapter.isEnabled()){
Toast.makeText(getApplicationContext(), "Turning on bluetooth..", Toast.LENGTH_SHORT).show();
Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetoothIntent, ENABLE_BT_REQUEST_CODE);
discoverDevices();
}else{
/* Toast.makeText(getApplicationContext(), "Bluetooth has already been enabled." +
"\n" + "Scanning for available nearby bluetooth devices..",
Toast.LENGTH_SHORT).show();*/
discoverDevices();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ENABLE_BT_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
// Toast.makeText(getApplicationContext(), "Bluetooth is now enabled.", Toast.LENGTH_SHORT).show();
discoverDevices();
} else {
// Toast.makeText(getApplicationContext(), "Bluetooth is not enabled.",Toast.LENGTH_SHORT).show();
toggleBtn.setChecked(false);
}
}
}
protected void discoverDevices(){
if (bluetoothAdapter.startDiscovery()) {
Toast.makeText(getApplicationContext(), "Scanning for available nearby bluetooth devices..", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Scanning failed to start.", Toast.LENGTH_SHORT).show();
}
}
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// Whenever a remote Bluetooth device is found
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
adapter.add(bluetoothDevice.getName() + "\n"
+ bluetoothDevice.getAddress());
}
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
Toast.makeText(getApplicationContext(), "Paired.", Toast.LENGTH_SHORT).show();
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
Toast.makeText(getApplicationContext(), "UnPaired.", Toast.LENGTH_SHORT).show();
}
}
}
};
#Override
protected void onResume() {
super.onResume();
// Register the BroadcastReceiver for ACTION_FOUND
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(broadcastReceiver, filter);
}
#Override
protected void onPause() {
super.onPause();
this.unregisterReceiver(broadcastReceiver);
}
private class ConnectingThread extends Thread {
private final BluetoothSocket bluetoothSocket;
private final BluetoothDevice bluetoothDevice;
public ConnectingThread(BluetoothDevice device) {
BluetoothSocket temp = null;
bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
System.out.println("1");
temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
System.out.println("2");
} catch (IOException e) {
System.out.println("In catch exception connecting bt device");
e.printStackTrace();
}
System.out.println("3");
bluetoothSocket = temp;
}
public void run() {
// Cancel discovery as it will slow down the connection
System.out.println("4");
bluetoothAdapter.cancelDiscovery();
try {
// This will block until it succeeds in connecting to the device
// through the bluetoothSocket or throws an exception
System.out.println("5");
if(bluetoothSocket!=null){
bluetoothSocket.connect();
}
/*InputStream inputStream = bluetoothSocket.getInputStream();
OutputStream outputStream = bluetoothSocket.getOutputStream();
outputStream.write(new byte[] { (byte) 0xa0, 0, 7, 16, 0, 4, 0 });*/
Log.e("","Connected");
} catch (IOException connectException) {
System.out.println("In connection exception thread");
connectException.printStackTrace();
try {
System.out.println("6");
bluetoothSocket.close();
System.out.println("7");
} catch (IOException closeException) {
System.out.println("in connection close exception");
closeException.printStackTrace();
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (bluetoothSocket != null) {
try {
Log.d("TCS", ">>Client Close");
bluetoothSocket.close();
finish();
return ;
} catch (IOException e) {
Log.e("EF-BTBee", "", e);
}
}
}
// Code to manage the connection in a separate thread
// manageBluetoothConnection(bluetoothSocket);
}
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord("tcs", uuid);
} catch (IOException e) { }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
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)
//manageConnectedSocket(socket);
try {
mmServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
}
This is my activity file. from where i am trying to connect another android device. But when trying to connect nothing happens. Just getting a warning getBluetoothService() called with no BluetoothManagerCallback.
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) {
}
}
}
}
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.