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;
}
Related
I am creating an application for working with a bluetooth device using the navigation drawer activity template, there was a problem with initializing the bluetooth adapter in a fragment, I attach my code below. When compiling the code, it gives the error
error: unreachable statement
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
package com.example.myt.ui.home;
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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
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 androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.ui.AppBarConfiguration;
import com.example.myt.R;
import java.io.IOException;
import java.util.Set;
import java.util.UUID;
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
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 BluetoothSocket socket;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private AppBarConfiguration mAppBarConfiguration;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
return root;
// 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(getActivity().getBaseContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
text = (TextView) root.findViewById(R.id.text);
onBtn = (Button) root.findViewById(R.id.turnOn);
onBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button) root.findViewById(R.id.turnOff);
offBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button) root.findViewById(R.id.paired);
listBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button) root.findViewById(R.id.search);
findBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView) root.findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
}
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
myBluetoothAdapter.cancelDiscovery();
final String info = ((TextView) arg1).getText().toString();
//get the device address when click the device item
String address = info.substring(info.length()-17);
//connect the device when item is click
BluetoothDevice connect_device = myBluetoothAdapter.getRemoteDevice(address);
try {
socket = connect_device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
} catch (IOException e) {
try {
socket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
}
});//************new_devices_list end
}
private void errorExit(String title, String message){
Toast.makeText(getActivity().getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
getActivity().finish();
}
public void on(View view){
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getActivity().getBaseContext(),"Bluetooth turned on" ,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getActivity().getBaseContext(),"Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BT) {
if (myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view){
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast.makeText(getActivity().getBaseContext(),"Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
getActivity().registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view){
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getActivity().getBaseContext(),"Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
}
You are returning the view immediately on onCreateView, which is why the rest of the code can never be reached. The issue is here:
View root = inflater.inflate(R.layout.fragment_home, container, false);
return root;
Place return root; after:
new_devices list end
I am having some difficulty passing the right information to set up Bluetooth discovery and pairing. I have been following the Android developer example documents pretty closely and have not been able to figure out what I need to pass to this method. This is the site I have been using, for reference.
http://developer.android.com/guide/topics/connectivity/bluetooth.html
TransferFragment:
//some code used from
// http://examples.javacodegeeks.com/android/core/ui/progressdialog/android-progressdialog-example/
// http://developer.android.com/guide/topics/connectivity/bluetooth.html
package com.project.BluetoothTransfer_v1000;
import java.util.Set;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class TransferFragment extends Fragment{
private TextView filePathTextView;
private Button startTransferButton;
private ImageView bluetoothImage;
ProgressDialog transferDialog;
Handler updateBarHandler;
private static final int REQUEST_BLUETOOTH = 1;
private static final int DISCOVER_DURATION = 300;
Context context;
ArrayAdapter mArrayAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, final Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//set the user interface layout for this activity
setRetainInstance(false);
View v = inflater.inflate(R.layout.activity_bluetooth_transfer, parent, false);
context = this.getActivity();
filePathTextView = (TextView) v.findViewById(R.id.file_path_textView);
startTransferButton = (Button) v.findViewById(R.id.start_transfer_button);
bluetoothImage = (ImageView) v.findViewById(R.id.bluetooth_imageView);
bluetoothImage.setClickable(true);
startTransferButton.setOnClickListener(new View.OnClickListener() {
//start transfer processes
#SuppressWarnings("unchecked")
#Override
public void onClick(View v){
//check to make sure the file path text view != null
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
int REQUEST_ENABLE_BT = -1;
//ensure the device being used has bluetooth capability
if (btAdapter != null){
//check-enable bluetooth
if (!btAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//ensure the textview isn't empty
//check if filepath is null
if (filePathTextView.getText().toString().length() != 0){
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
//check if there are paired devices
if (pairedDevices.size() > 0){
//loop through paired devices
for (BluetoothDevice device: pairedDevices){
//add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}//end found paired devices if
// Create a BroadcastReceiver for ACTION_FOUND
final BroadcastReceiver mReceiver = 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 address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
//COMPILER ERROR BELOW ######################################################
//"This method registerReceiver(BroadcastReceiver, IntentFilter)
//is undefined for type new View.OnClickListener
registerReceiver(mReceiver, filter);
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
btAdapter.cancelDiscovery();
}//
else {
//alert user to input file path
new AlertDialog.Builder(context).setTitle("Error")
.setMessage("Please insert a filename to send.")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
}).show();
}//ifnull (else)
}//bt equipped check
}//end anon class
});
bluetoothImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//display dialog showing program specs and creators
new AlertDialog.Builder(context).setTitle("About")
.setMessage("Created by:"+"\n"+ "Hal, Chris, and Roger")
.setPositiveButton("Awesome!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
});
return v;
}
}
TransferActivity:
package com.project.BluetoothTransfer_v1000;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class TransferActivity extends FragmentActivity{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transfer);
TransferFragment fragment = new TransferFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container, fragment);
fragmentTransaction.commit();
}
}
Try:
TransferFragment.this.getActivity().registerReceiver(mReceiver, filter);
Instead of:
registerReceiver(mReceiver, filter);
Because the method registerReceiver is part of the Activity and not the OnClickListener. This is why the error message complains about not found method in OnClickListener:
This method registerReceiver(BroadcastReceiver, IntentFilter)
is undefined for type new View.OnClickListener
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));
}
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();
}
}
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>