Connecting 2 bluetooth devices - android

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.

Related

Data sent from Android to HC-05 Bluetooth Arduino not showing

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

I am building a bluetooth app for communating another bluetooth device. I am able to scan and get list of available devices

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.

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

Android + Pair devices via bluetooth programmatically

I want to discover bluetooth devices in range, list and pair to them on click. I used following code but its just closing application when I click on device name which I want to pair.
I want to know mistake in my code or any other way to do what i need.
package com.marakana;
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.view.Window;
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.AdapterView.OnItemClickListener;
public class BluetoothDemo extends Activity {
// Debugging
private static final String TAG = "DeviceListActivity";
private static final boolean D = true;
// Return Intent extra
public static String EXTRA_DEVICE_ADDRESS = "device_address";
// Member fields
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the window
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
// Set result CANCELED incase the user backs out
setResult(Activity.RESULT_CANCELED);
// Initialize the button to perform device discovery
Button scanButton = (Button) findViewById(R.id.button_scan);
scanButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
doDiscovery();
v.setVisibility(View.GONE);
}
});
// Initialize array adapters. One for already paired devices and
// one for newly discovered devices
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
// Find and set up the ListView for paired devices
ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
// Find and set up the ListView for newly discovered devices
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
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);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
/**
* Start device discover with the BluetoothAdapter
*/
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 (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
}
// The on-click listener for all devices in the ListViews
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.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();
}
};
// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
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);
// 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);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
}
In my first answer the logic is shown for those who want to go with the logic only.
I think I was not able to make clear to #chalukya3545, that's why I am adding the whole code to let him know the exact flow of the code.
BluetoothDemo.java
public class BluetoothDemo extends Activity {
ListView listViewPaired;
ListView listViewDetected;
ArrayList<String> arrayListpaired;
Button buttonSearch,buttonOn,buttonDesc,buttonOff;
ArrayAdapter<String> adapter,detectedAdapter;
static HandleSeacrh handleSeacrh;
BluetoothDevice bdDevice;
BluetoothClass bdClass;
ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
private ButtonClicked clicked;
ListItemClickedonPaired listItemClickedonPaired;
BluetoothAdapter bluetoothAdapter = null;
ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
ListItemClicked listItemClicked;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listViewDetected = (ListView) findViewById(R.id.listViewDetected);
listViewPaired = (ListView) findViewById(R.id.listViewPaired);
buttonSearch = (Button) findViewById(R.id.buttonSearch);
buttonOn = (Button) findViewById(R.id.buttonOn);
buttonDesc = (Button) findViewById(R.id.buttonDesc);
buttonOff = (Button) findViewById(R.id.buttonOff);
arrayListpaired = new ArrayList<String>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
clicked = new ButtonClicked();
handleSeacrh = new HandleSeacrh();
arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice>();
/*
* the above declaration is just for getting the paired bluetooth devices;
* this helps in the removing the bond between paired devices.
*/
listItemClickedonPaired = new ListItemClickedonPaired();
arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
adapter= new ArrayAdapter<String>(BluetoothDemo.this, android.R.layout.simple_list_item_1, arrayListpaired);
detectedAdapter = new ArrayAdapter<String>(BluetoothDemo.this, android.R.layout.simple_list_item_single_choice);
listViewDetected.setAdapter(detectedAdapter);
listItemClicked = new ListItemClicked();
detectedAdapter.notifyDataSetChanged();
listViewPaired.setAdapter(adapter);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
getPairedDevices();
buttonOn.setOnClickListener(clicked);
buttonSearch.setOnClickListener(clicked);
buttonDesc.setOnClickListener(clicked);
buttonOff.setOnClickListener(clicked);
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);
}
}
adapter.notifyDataSetChanged();
}
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);
//bdClass = arrayListBluetoothDevices.get(position);
Log.i("Log", "The dvice : "+bdDevice.toString());
/*
* here below we can do pairing without calling the callthread(), we can directly call the
* connect(). but for the safer side we must usethe threading object.
*/
//callThread();
//connect(bdDevice);
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
//arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
//adapter.notifyDataSetChanged();
getPairedDevices();
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}//connect(bdDevice);
Log.i("Log", "The bond is created: "+isBonded);
}
}
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 void callThread() {
new Thread(){
public void run() {
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//connect(bdDevice);
Log.i("Log", "The bond is created: "+isBonded);
}
}.start();
}*/
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);
Object[] args = {};
bool = (Boolean) method.invoke(bdDevice);//, args);// this invoke creates the detected devices paired.
//Log.i("Log", "This is: "+bool.booleanValue());
//Log.i("Log", "devicesss: "+bdDevice.getName());
} 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();
}
class ButtonClicked implements OnClickListener
{
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonOn:
onBluetooth();
break;
case R.id.buttonSearch:
arrayListBluetoothDevices.clear();
startSearching();
break;
case R.id.buttonDesc:
makeDiscoverable();
break;
case R.id.buttonOff:
offBluetooth();
break;
default:
break;
}
}
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
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);
try
{
//device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
//device.getClass().getMethod("cancelPairingUserInput", boolean.class).invoke(device);
}
catch (Exception e) {
Log.i("Log", "Inside the exception: ");
e.printStackTrace();
}
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(int 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();
}
}
}
}
};
private void startSearching() {
Log.i("Log", "in the start searching method");
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
BluetoothDemo.this.registerReceiver(myReceiver, intentFilter);
bluetoothAdapter.startDiscovery();
}
private void onBluetooth() {
if(!bluetoothAdapter.isEnabled())
{
bluetoothAdapter.enable();
Log.i("Log", "Bluetooth is Enabled");
}
}
private void offBluetooth() {
if(bluetoothAdapter.isEnabled())
{
bluetoothAdapter.disable();
}
}
private void makeDiscoverable() {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
Log.i("Log", "Discoverable ");
}
class HandleSeacrh extends Handler
{
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 111:
break;
default:
break;
}
}
}
}
Here is the main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/buttonOn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="On"/>
<Button
android:id="#+id/buttonDesc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Make Discoverable"/>
<Button
android:id="#+id/buttonSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Search"/>
<Button
android:id="#+id/buttonOff"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bluetooth Off"/>
<ListView
android:id="#+id/listViewPaired"
android:layout_width="match_parent"
android:layout_height="120dp">
</ListView>
<ListView
android:id="#+id/listViewDetected"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
Add this permissions to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
The output for this code will look like this.
The Best way is do not use any pairing code.
Instead of onClick go to other function or other class where You create the socket using UUID.
Android automatically pops up for pairing if already not paired.
or see this link for better understanding
Below is code for the same:
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.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);
// **add this 2 line code**
Intent myIntent = new Intent(view.getContext(), Connect.class);
startActivityForResult(myIntent, 0);
finish();
}
};
Connect.java file is :
public class Connect extends Activity {
private static final String TAG = "zeoconnect";
private ByteBuffer localByteBuffer;
private InputStream in;
byte[] arrayOfByte = new byte[4096];
int bytes;
public BluetoothDevice mDevice;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connect);
try {
setup();
} catch (ZeoMessageException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ZeoMessageParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void setup() throws ZeoMessageException, ZeoMessageParseException {
// TODO Auto-generated method stub
getApplicationContext().registerReceiver(receiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
getApplicationContext().registerReceiver(receiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
BluetoothDevice zee = BluetoothAdapter.getDefaultAdapter().
getRemoteDevice("**:**:**:**:**:**");// add device mac adress
try {
sock = zee.createRfcommSocketToServiceRecord(
UUID.fromString("*******************")); // use unique UUID
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Connecting");
try {
sock.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Connected");
try {
in = sock.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Listening...");
while (true) {
try {
bytes = in.read(arrayOfByte);
Log.d(TAG, "++++ Read "+ bytes +" bytes");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Done: test()");
}}
private static final LogBroadcastReceiver receiver = new LogBroadcastReceiver();
public static class LogBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent) {
Log.d("ZeoReceiver", paramAnonymousIntent.toString());
Bundle extras = paramAnonymousIntent.getExtras();
for (String k : extras.keySet()) {
Log.d("ZeoReceiver", " Extra: "+ extras.get(k).toString());
}
}
};
private BluetoothSocket sock;
#Override
public void onDestroy() {
getApplicationContext().unregisterReceiver(receiver);
if (sock != null) {
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
super.onDestroy();
}
}
if you have the BluetoothDevice object you can create bond(pair) from api 19 onwards with bluetoothDevice.createBond() method.
Edit
for callback, if the request was accepted or denied you will have to create a BroadcastReceiver with BluetoothDevice.ACTION_BOND_STATE_CHANGED action
Edit: I have just explained logic to pair here. If anybody want to go with the complete code then see my another answer. I have answered here for logic only but I was not able to explain properly, So I have added another answer in the same thread.
Try this to do pairing:
If you are able to search the devices then this would be your next step
ArrayList<BluetoothDevice> arrayListBluetoothDevices = NEW ArrayList<BluetoothDevice>;
I am assuming that you have the list of Bluetooth devices added in the arrayListBluetoothDevices:
BluetoothDevice bdDevice;
bdDevice = arrayListBluetoothDevices.get(PASS_THE_POSITION_TO_GET_THE_BLUETOOTH_DEVICE);
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
Log.i("Log","Paired");
}
} catch (Exception e)
{
e.printStackTrace();
}
The createBond() method:
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();
}
Add this line into your Receiver in the ACTION_FOUND
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
arrayListBluetoothDevices.add(device);
}

Categories

Resources