Hi i have a curiouse problem, i m making one program which has to connect to heart rate monitor via bluetooth, i write a code which is valid but when i run the program i falls.I also have a problem to debug it because the bluetooth i can only test on real device
here is my class where it falls:
package sk.Csabi.Test.TestBluetooth;
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;
/**
* This Activity appears as a dialog. It lists any paired devices and
* devices detected in the area after discovery. When a device is chosen
* by the user, the MAC address of the device is sent back to the parent
* Activity in the result Intent.
*/
public class DeviceListActivity 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);
}
}
}
};
}
I call it after when the bluetooth is turned on like this:
final Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent serverIntent = new Intent(mContext, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
}
If you gave me a tip how can i debug it on computer i will, thanks
});
try {
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
} catch (exception e) {
//set some view field to the exception message
}
Any time you start something you should put it in a try catch in case it fails. You should probably also look into running that process in a separate thread and passing whatever data you need back to the UI activity else the UI is going to be unresponsive and the application/phone will not be able to do anything until android automagickly kills the app.
Related
I have the following code to discover Bluetooth devices and get list of devices nearby and connect with it. i would like to use set MAC ID to pass to connect to print without clicking process.
the main purpose is to automatically connect the device on create
for example i got printer has following address.
PRINTER_MAC_ID = "00:03:7A:25:1E:D8";
how i can put above code to get device connected automatically
below code gets the list of devices and pair it on click.
package com.new.print;
import java.util.Set;
import com.zj.btsdk.BluetoothService;
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;
/**
* This Activity appears as a dialog. It lists any paired devices and
* devices detected in the area after discovery. When a device is chosen
* by the user, the MAC address of the device is sent back to the parent
* Activity in the result Intent.
*/
public class DeviceListActivity extends Activity {
// Return Intent extra
public static String EXTRA_DEVICE_ADDRESS = "device_address";
// Member fields
BluetoothService mService = null;
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);
mService = new BluetoothService(this, null);
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mService.getPairedDev();
// 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();
if (mService != null) {
mService.cancelDiscovery();
}
mService = null;
this.unregisterReceiver(mReceiver);
}
/**
* Start device discover with the BluetoothAdapter
*/
private void 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 (mService.isDiscovering()) {
mService.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mService.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
mService.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);
Log.d("Á¬½ÓµØÖ·", 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);
}
}
}
};
}
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));
}
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.
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.
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>