How to calculate distance between two android device using Bluetooth signal strength? - android

I'm working on android application. In my project I want to show Bluetooth scanning device, MAC Address, Bluetooth signal strength and Distance between two Android device.
I have done 3 requirements but I don't know how to get distance using Signal strength.
package com.example.bluetoothdemo;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.BroadcastReceiver;
public class MainActivity extends Activity {
private BluetoothAdapter BTAdapter = BluetoothAdapter.getDefaultAdapter();
private static final int REQUEST_ENABLE_BT = 1;
ListView listDevicesFound;
Button btnScanDevice;
TextView stateBluetooth;
BluetoothAdapter bluetoothAdapter;
ArrayAdapter<String> btArrayAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnScanDevice = (Button)findViewById(R.id.scan_device);
stateBluetooth = (TextView)findViewById(R.id.textView1);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
listDevicesFound = (ListView)findViewById(R.id.listView1);
btArrayAdapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1);
listDevicesFound.setAdapter(btArrayAdapter);
CheckBlueToothState();
btnScanDevice.setOnClickListener(btnScanDeviceOnClickListener);
registerReceiver(ActionFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(ActionFoundReceiver);
}
private void CheckBlueToothState(){
if (bluetoothAdapter == null){
stateBluetooth.setText("Bluetooth NOT support");
}else{
if (bluetoothAdapter.isEnabled()){
if(bluetoothAdapter.isDiscovering()){
stateBluetooth.setText("Bluetooth is currently in device discovery process.");
}else{
stateBluetooth.setText("Bluetooth is Enabled.");
btnScanDevice.setEnabled(true);
}
}else{
stateBluetooth.setText("Bluetooth is NOT Enabled!");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
private Button.OnClickListener btnScanDeviceOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
btArrayAdapter.clear();
bluetoothAdapter.startDiscovery();
}};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
CheckBlueToothState();
}
}
private final BroadcastReceiver ActionFoundReceiver = 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);
btArrayAdapter.add(device.getName() + "\n" + device.getAddress()+ "
\n "+intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE));
btArrayAdapter.notifyDataSetChanged();
}
}};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private final BroadcastReceiver receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
String name = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
TextView rssi_msg = (TextView) findViewById(R.id.listView1);
Toast.makeText(getApplicationContext()," RSSI: " + rssi + "dBm",
Toast.LENGTH_SHORT).show();
}
}
};
}

Try using the "b and l bluetooth le scanner" app from the Google Play Store, to visualize the signals from several Bluetooth LE devices. You will immediately discover that the rssi signal strengths are "noisy" when multiple devices are present. Walls, furniture with metal components, and Wi-Fi sources will also cause signal variations. The best solution is to create "zones" for your distance readings... Something like: far, close, next-to, etc.

That is practically not possible to calculate the distance based on only the bluetooth signal strength. You can however use the triangulation technique to get the distance between the two devices or altogether can use the GPS concept to find out the distance.
Using only bluetooth, finding distance is not possible.
Even though you can do something like this to denote the signal strength in an easy understandable way.
https://play.google.com/store/apps/details?id=com.bluetoothFinder
see this link.

You can calculate distance by using txPower. Below is a mathematical way to calculate this.
double getDistance(int rssi, int txPower) {
return Math.pow(10d, ((double) txPower - rssi) / (10 * 2));
}

Related

Listing Android Bluetooth devices

This is totally in sane, I got my app working 100% (it's only listing devices not doing any connection) but when i execute it it doesnt appear any Bluetooth device in my ListView, the funniest part is that when I execute it with debugger they DO appear. Here you have my code, I have been looking at it for the last 3 hours, hope you can land me a hand :(
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
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.view.Menu;
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 ListarDispositivos extends ListActivity {
//this, R.layout.activity_listar_dispositivos, s
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
private static String EXTRA_DEVICE_ADDRESS = "device_address";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listar_dispositivos);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.nombres_dispositivos,R.id.txvNombreDispositivo);
ListView listview = getListView();
setListAdapter(mNewDevicesArrayAdapter);
//listview.setOnItemClickListener(mDeviceClickListener);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
doDiscovery();
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
mBtAdapter.disable();
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
private void doDiscovery() {
// Indicate scanning in the title
setTitle("Escaneando");
// If we're already discovering, stop it
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
Toast toast1 =
Toast.makeText(getApplicationContext(),
"Estoy buscando", Toast.LENGTH_SHORT);
toast1.show();
}
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();
}
};
//Salta cada vez que encuentra un dispositivo o eso deberia el cabron
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)) {
setTitle("Elija dispositivo");
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = "No encontrado";
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.listar_dispositivos, menu);
return true;
}
}
After adding found devices to the mNewDevicesArrayAdapter, you should call notifyDataSetChanged() so that the listview is refreshed.

How to add the content into ListView by use the ListView and ArrayAdapter?

I am developing an application where I have to connect to a Bluetooth device.
When I click the btn_discover Button, it will call BroadcastReceiver and scan the new bluetooth device and show on the TextView.
When I use the TextView, I can see the bluetooth device on Textview.
And now I want to change the TextView to ListView.
But it always crashes. When in BroadcastReceiver's onReceive(), I write:
newDevicelistArrayAdapter.add(device.getName());
This is my Java Code:
package com.example.bttest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import com.example.bttest.R.menu;
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 android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Main extends Activity {
public BluetoothAdapter mBluetoothAdapter;
private static final int REQUEST_SELECT_DEVICE = 1;
public Button btn_scan;
public Button btn_discover;
public TextView pair_list;
public TextView scan_list;
public ListView scan_list_1;
public Set<BluetoothDevice> pairedDevices;
public ArrayAdapter<String> newDevicelistArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_scan = (Button)findViewById(R.id.btn_scan);
btn_discover = (Button)findViewById(R.id.btn_discover);
pair_list = (TextView)findViewById(R.id.pair_list);
scan_list = (TextView)findViewById(R.id.scan_list);
newDevicelistArrayAdapter = new ArrayAdapter<String>(this, R.layout.main);
scan_list_1 = (ListView)findViewById(R.id.scan_list_1);
scan_list_1.setAdapter(newDevicelistArrayAdapter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null)
{
Toast.makeText(this, "No support bluetooth", Toast.LENGTH_SHORT).show();
return;
}else if(mBluetoothAdapter != null) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_SELECT_DEVICE);
}
//******************scan按鈕動作-將已配對過的藍芽裝置列出來
btn_scan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size()>0) {
for(BluetoothDevice bDevice : pairedDevices) {
pair_list.append(bDevice.getName() + "\n" + bDevice.getAddress() + "\n" + bDevice.getBondState() + "\n" );
}
}
}
});
//******************scan按鈕動作結束
btn_discover.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
mBluetoothAdapter.startDiscovery();
}
});
}
private final BroadcastReceiver mReceiver = 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);
scan_list.append(device.getName() + "\n" + device.getAddress() + "\n");
newDevicelistArrayAdapter.add(device.getName());
}
}
};
protected void onDestroy() {
super.onDestroy();
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
unregisterReceiver(mReceiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Does it any wrong when I use the ListView and ArrayAdapter?
Replace the onReceive() of your BroadcastReceiver with this:
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);
scan_list.append(device.getName() + "\n" + device.getAddress() + "\n");
newDevicelistArrayAdapter.notifyDataSetChanged();
}
}

How to connect the Bluetooth device by click the item of listview in Android?

I am developing an application where I have to connect to Bluetooth device on Android 4.3.
I can scan the bluetooth device, but it can not connect the bluetooth device.
I have already add the permission in Manifest of the following:
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
My Operation is when I push SCAN Button, it will scan the Bluetooth device and show on the ListView.
When I click the bluetooth device on ListView,it will connect the bluetooth device of item.
But when I click the device item, the app will crash, and I don't know why...
This is my java code:
package com.example.preventthelost;
import java.io.IOException;
import java.net.Socket;
import java.util.Set;
import java.util.UUID;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
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.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class DeviceList extends Activity {
protected static final String tag = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private static final int REQUEST_ENABLE_BT=1;
private Button btn_cancel;
private Button btn_scan;
private ListView pair_devices_list;
private ListView new_devices_list;
private Set<BluetoothDevice> pairedDevice;
private ArrayAdapter<String> newDevicelistArrayAdapter;
private ArrayAdapter<String> pairDevicelistArrayAdapter;
private final UUID my_UUID = UUID.fromString("00001802-0000-1000-8000-00805f9b34fb");
//private final UUID my_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothSocket socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_list);
btn_scan = (Button)findViewById(R.id.btn_scan);
newDevicelistArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
new_devices_list = (ListView)findViewById(R.id.new_devices_list);
new_devices_list.setAdapter(newDevicelistArrayAdapter);
         **//check device support bluetooth or not**
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null) {
Toast.makeText(this, "No support bluetooth", Toast.LENGTH_SHORT).show();
finish();
return;
}else if(!mBluetoothAdapter.isEnabled()){ **//if bluetooth is close, than open it**
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBTIntent, REQUEST_ENABLE_BT);
}
**//click the scan button**
btn_scan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//**list the bluetooth device**
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
mBluetoothAdapter.startDiscovery();
newDevicelistArrayAdapter.clear();
}
});
//new_devices_list click
new_devices_list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
mBluetoothAdapter.cancelDiscovery();
final String info = ((TextView) arg1).getText().toString();
             //get the device address when click the device item
String address = info.substring(info.length()-19);
//connect the device when item is click
          BluetoothDevice connect_device = mBluetoothAdapter.getRemoteDevice(address);
try {
socket = connect_device.createRfcommSocketToServiceRecord(my_UUID);
socket.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});//************new_devices_list end
}
public final BroadcastReceiver mReceiver = 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 bdevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//short rssi = intent.getExtras().getShort(BluetoothDevice.EXTRA_RSSI);;
if(bdevice.getBondState() != BluetoothDevice.BOND_BONDED)
newDevicelistArrayAdapter.add("\n" + bdevice.getName() + "\n" + bdevice.getAddress());
newDevicelistArrayAdapter.notifyDataSetChanged();
}
}
};
protected void onDestroy() {
super.onDestroy();
if(mBluetoothAdapter != null)
mBluetoothAdapter.cancelDiscovery();
unregisterReceiver(mReceiver);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.device_list, menu);
return true;
}
}
when I type the connect code of following into new_devices_list.setOnItemClickListener, it always crash.
//get the device address when click the device item
String address = info.substring(info.length()-19);
//connect the device when item is click
BluetoothDevice connect_device = mBluetoothAdapter.getRemoteDevice(address);
try {
socket = connect_device.createRfcommSocketToServiceRecord(my_UUID);
socket.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am not sure, but the problem look like in this line:
BluetoothDevice connect_device = mBluetoothAdapter.getRemoteDevice(address);
The data type of the address is String rather address.
But the type of getRemoteDevice I choose is String address.
SO...I don't know Why the app always crash when I type the connect code in new_devices_list even??
Does it can not be use in Android 4.3 ??
Can someone teach me??
Thanks!!
It was not clear if you are connecting Bluetooth Classic or a Low Energy device. Your code is for Classic, the tag suggests Low Energy. In case the Low Energy you would use
device.connectGatt(this, false, mGattCallback);
instead of
connect_device.createRfcommSocketToServiceRecord(my_UUID);
You select Tag BluetoothLowEnergy. Your question is about BLE or standard Bluetooth? for BLE there is another approach to connect. You can read here
I had a similar problem, but just found a solution.
Instead of subtracting 19 from info.length() in
String address = info.substring(info.length()-19);
subtract 17 instead. The original post is posted almost a year ago, but hopefully it's still helpful to those who have the same problem.

Android Bluetooth printer

I am trying to make an android bluetooth printer application, in which I am successful in detecting bluetooth devices in my proximity,but I am not able to set up a connection when one of the device is choose for connection. also as I am trying to get names of devices in a listview,it is showing one name many times. I am posting my code below.please help
package com.example.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;
import android.os.Bundle;
import android.os.Handler;
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.view.Menu;
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;
OutputStream mmOutputStream;
ListView listDevicesFound;
Button btnScanDevice,connect;
TextView stateBluetooth;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
List<String> discoverableDevicesList;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
ArrayAdapter<String> btArrayAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnScanDevice = (Button)findViewById(R.id.scandevice);
stateBluetooth = (TextView)findViewById(R.id.bluetoothstate);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
connect = (Button)findViewById(R.id.button2);
listDevicesFound = (ListView)findViewById(R.id.devicesfound);
btArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
listDevicesFound.setAdapter(btArrayAdapter);
CheckBlueToothState();
btnScanDevice.setOnClickListener(btnScanDeviceOnClickListener);
registerReceiver(ActionFoundReceiver,
new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(ActionFoundReceiver);
}
private void CheckBlueToothState(){
if (mBluetoothAdapter == null){
stateBluetooth.setText("Bluetooth NOT support");
}else{
if (mBluetoothAdapter.isEnabled()){
if(mBluetoothAdapter.isDiscovering()){
stateBluetooth.setText("Bluetooth is currently in device discovery process.");
}else{
stateBluetooth.setText("Bluetooth is Enabled.");
btnScanDevice.setEnabled(true);
}
}else{
stateBluetooth.setText("Bluetooth is NOT Enabled!");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
private Button.OnClickListener btnScanDeviceOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
btArrayAdapter.clear();
mBluetoothAdapter.startDiscovery();
}};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
CheckBlueToothState();
}
}
private final BroadcastReceiver ActionFoundReceiver = 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);
btArrayAdapter.add(device.getName() + "\n" + device.getAddress());
btArrayAdapter.notifyDataSetChanged();
}
}
};}
This is Dialog to show all Paired devices in ListView.
public Dialog pushDevicePairDialog(){
_mDeviceListView = ((LayoutInflater) _mCallingActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.bluetooth_devices_list, null, false);
_mDeviceListDialog = new Dialog(_mCallingActivity,R.style.ThemeDialogCustom);
_mDeviceListDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
_mDeviceListDialog.setContentView(_mDeviceListView);
_mDeviceListDialog.setCancelable(true);
_mPairedDevicesArrayAdapter = new ArrayAdapter<String>(_mCallingActivity,R.layout.device_name);
_mNewDevicesArrayAdapter = new ArrayAdapter<String>(_mCallingActivity,R.layout.device_name);
Button scanButton = (Button) _mDeviceListView.findViewById(R.id.button_scan);
scanButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
doDiscovery();
v.setVisibility(View.GONE);
}
});
ListView pairedListView = (ListView) _mDeviceListView.findViewById(R.id.paired_devices);
pairedListView.setAdapter(_mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(_mDeviceClickListener);
ListView newDevicesListView = (ListView) _mDeviceListView.findViewById(R.id.new_devices);
newDevicesListView.setAdapter(_mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(_mDeviceClickListener);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
_mCallingActivity.registerReceiver(_mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
_mCallingActivity.registerReceiver(_mReceiver, filter);
_mBtAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = _mBtAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
_mDeviceListView.findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
String devName = device.getName();
if(devName != null && (devName.startsWith("ESYS") || devName.startsWith("ACC")))
_mPairedDevicesArrayAdapter.add(devName + "\n" + device.getAddress());
}
} else {
String noDevices = _mCallingActivity.getResources().getText(R.string.none_paired).toString();
_mPairedDevicesArrayAdapter.add(noDevices);
}
if (_mBluetoothService == null)
_mBluetoothService = new BluetoothConnectorService(_mCallingActivity);
_mBluetoothService.setListener(this);
return _mDeviceListDialog;
}

Android - Bluetooth find device error

I'm new here so I apologize if I wrote something bad
I got some error in my code that should find some but device (in Eclipse it looks ok but it shows some Force Quit while I'm clicking button Find Device :(
Code
package com.moj.test;
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.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Bluetooth extends Activity{
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private static final int REQUEST_ENABLE_BT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth);
Button bStart = (Button) findViewById(R.id.btbutton1);
Button bFind = (Button) findViewById(R.id.btbutton2);
bStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
BluetoothStart();
}
});
bFind.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
mBluetoothAdapter.startDiscovery();
}
});
}
public void BluetoothStart() {
if (mBluetoothAdapter != null) {
if (!mBluetoothAdapter.isEnabled()) {
//Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), REQUEST_ENABLE_BT);
}
}
}
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
EditText te = (EditText) findViewById(R.id.editText1);
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 address to an array adapter to show in a ListView
te.setText(device.getName() + "\n" + device.getAddress());
}
}
};
}
You cant run this on Emulator because it doesn't have support for Bluetooth. You need to test it on a real device.
And don't forget to include Bluetooth permission in manifest.
<manifest ... >
<uses-permission android:name="android.permission.BLUETOOTH" />
...
</manifest>

Categories

Resources