Listing Android Bluetooth devices - android

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.

Related

how to search unpaired bluetooth devices?

I'm doing an app which uses bluetooth communication.
At first, I'm trying to get a list of all bluetooth devices detectable by the device.
I've managed to load in a listview all the paired devices, but i'm unable to list un-paired devices, I've found some tutorials but I'm a bit confused as I'm a bit new to android development & bluetooth communication.
So i need to find every bluetooth device in range, and I don't know how to do it (lazy)
Here is the (edited) code:
package com.voice.benz.instaurentremote;
import android.bluetooth.*;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.widget.ArrayAdapter;
import java.util.Set;
import android.content.Context;
import android.content.BroadcastReceiver;
import android.view.Window;
import android.app.Activity;
import android.content.IntentFilter;
import android.util.Log;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemClickListener;
import java.util.ArrayList;
public class bluetooth extends ActionBarActivity {
private TextView bluetoothPaired;
private TextView txt_status;
private BluetoothAdapter btAdapter;
private ListView newdevices_listview;
private Set<BluetoothDevice>pairedDevices;
private ArrayAdapter<String> adapter = null;
private static final int BLUETOOTH_ON = 1000;
private static final int REQUEST_ENABLE_BT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
// Initialize the button to perform device discovery
txt_status = (TextView) findViewById(R.id.txt_status);
newdevices_listview = (ListView)findViewById(R.id.newdevices_listview);
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
newdevices_listview.setAdapter(adapter);
// Initialize adapter
btAdapter = BluetoothAdapter.getDefaultAdapter();
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
//discovery starts, we can show progress dialog or perform other tasks
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//discovery finishes, dismis progress dialog
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//bluetooth device found
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
txt_status.setText("Found device " + device.getName());
adapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
public void attivaBluetooth (View view) {
if (!btAdapter.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 1);
}
}
public void cercaDispositivi (View view)
{
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
btAdapter.startDiscovery();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(mReceiver);
}
public void disattivaBluetooth (View view)
{
if (btAdapter.isEnabled())
{
btAdapter.disable();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bluetooth, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You don't seem to be registering your BroadcastReceiver myBluetoothReceiver anywhere. If you do that in onResume() or onCreate you'll probably have more luck. :)

Set direct MAC ID to Bluetooth Printer

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

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.

Bluetooth find device falls the program

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.

Categories

Resources