Discovering available bluetooth devices in android - android

I just started learning Android development. I am writing an Android program to scan available bluetooth devices and list them in a log file. As I am new to Android, I am unable to figure out what is wrong in the below code snippet.
button2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
ListView lv1 = (ListView) findViewById(R.id.myListView1);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
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);
Log.v("BlueTooth Testing",device.getName() + "\n"
+ device.getAddress());
}
}
};
String aDiscoverable = BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE;
startActivityForResult(new Intent(aDiscoverable),DISCOVERY_REQUEST);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
mBluetoothAdapter.startDiscovery();
}
});
When I try the debug mode, the control skips the "BroadcastReceiver()". I could not find any entries in the log. Can you help me in figuring out what the problem is and how I can list the available bluetooth devices.
[edit]
I am getting error that the application has stopped unexpectedly:
Logcat Errors:
10-28 20:08:24.201: ERROR/UpdateReceiver(914): ACTION_PACKAGE_REMOVED
10-28 20:08:28.415: ERROR/RequestPermissionActivity(431): Timeout = 120
10-28 20:08:44.291: ERROR/DTUN_HCID4(521): === dtunops_stop_discovery() ===

You should have the BLUETOOTH and BLUETOOTH_ADMIN permissions in your manifest

Related

How to get notified when each time bluetooth device is paired with any devices and when it device finds any paired devices get notification?

When device gets paired to any device i should get a notification and also if it finds any paired device aroud i should get notified .
How to achieve this using Broadcast reciever
Based on your comment i understand that you want to show if there is a nearby paired bluetooth device after bluetooth is connected..
so first after your BluetoothDevice.ACTION_ACL_CONNECTED you need to start scan for paired Bluetooth devices and display them in a list. In the context of a mobile device, a Bluetooth device can either be:
1)unknown
2)paired
3)connected
It is important to know the difference between a paired and a connected Bluetooth device. Paired devices are aware of each other’s existence and share a link key, which can be used to authenticate, resulting in a connection. Devices are automatically paired once an encrypted connection is established.
Bluetooth devices are represented by the BluetoothDevice object. A list of paired devices can be obtained by invoking the getBondedDevices() method.
In your activity class
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BTAdapter = BluetoothAdapter.getDefaultAdapter();
if (!BTAdapter.isEnabled()) {
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, REQUEST_BLUETOOTH);
}
Log.d("DEVICELIST", "Super called for DeviceListFragment onCreate\n");
deviceItemList = new ArrayList<DeviceItem>();
Set<BluetoothDevice> pairedDevices = bTAdapter.getBondedDevices();
}
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
DeviceItem newDevice= new DeviceItem(device.getName(),device.getAddress(),"false");
deviceItemList.add(newDevice);
}
}
then create a new clsss DevicelistFragment to make a BroadcastReceiver and override the onReceive() method. The onReceive() method is invoked whenever a Bluetooth device is found.
public class DeviceListFragment extends Fragment implements AbsListView.OnItemClickListener{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_deviceitem_list, container, false);
ToggleButton scan = (ToggleButton) view.findViewById(R.id.scan);
...
scan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
if (isChecked) {
mAdapter.clear();
getActivity().registerReceiver(bReciever, filter);
bTAdapter.startDiscovery();
} else {
getActivity().unregisterReceiver(bReciever);
bTAdapter.cancelDiscovery();
}
}
});
}
...
private final BroadcastReceiver bReciever = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Create a new device item
DeviceItem newDevice = new DeviceItem(device.getName(), device.getAddress(), "false");
// Add it to our adapter
mAdapter.add(newDevice);
}
}
};
}
For full project see https://github.com/tutsplus/Android-BluetoothScannerFinishedProject
Also see: http://www.londatiga.net/it/programming/android/how-to-programmatically-scan-or-discover-android-bluetooth-device/
//Try this snippet and handle the
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// 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());
//or handle here with notification.....
}
}
//you can get notified when a new device is connected using Broadcast receiver
BroadcastReceiver btReceive=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//the device is found
}
}
};

detecting all the bluetooth devices present in an area including the devices which are already paired

I am willing to generate a list which has the list of all the bluetooth enabled devices in the phone's vicinity. The code which I have discovers the devices which are not paired. Is there a way to retrieve the devices which are also paired (if they fall with the vicinity)
The code which discovers all the devices in the vicinity is as follows
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_connection);
final TextView tv=(TextView)findViewById(R.id.textView1);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
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);
tv.append(device.getName() + "-"+ device.getAddress()+"\n");
}
}
};
String aDiscoverable = BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE;
startActivityForResult(new Intent(aDiscoverable),DISCOVERY_REQUEST);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
mBluetoothAdapter.startDiscovery();
}
Can any one help me out in adding the code which discovers even the devices which are paired.
Thanks,
Set<BluetoothDevice> devices = adapter.getBondedDevices();
for (BluetoothDevice device : devices) {
tv.append(device);
}
I haven't tested this. It's from this tutorial.

16s time delay until the bluetooth disconnected request is recognized

I am working with a bluetooth device (the IOIO developer board).
I want to listen, when my device is disconnected. It is working ok with the code above, but it is not recognized instantaneously. When I power off my bluetooth developer board, I have to wait ~16s until my Android recognized that the connection was lost.
Does anybody know why? I heard it should be a internal Android limitation, that the connection is not checked so often?
Does anybody know how to write a thread which "pings" the bluetooth device if it is still there? I think it is very similar to the Android BluetoothChat example, but I couldn't fixed it on my own.
Thanks.
Felix
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter1);
this.registerReceiver(mReceiver, filter2);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
//Device is about to disconnect
Toast.makeText(context,"The device is about to disconnect" , Toast.LENGTH_LONG).show();
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//Device has disconnected
Toast.makeText(context,"Device has disconnected" , Toast.LENGTH_LONG).show();
}
}
};

Android Bluetooth enable

I am developing a Bluetooth chat application. The problem is that when i enable Bluetooth the application enables Bluetooth but causes force close. the next time i launch the same application(with Bluetooth enabled) it works smoothly ! i have searched and only got some information saying that when i start the intent for enable Bluetooth the code proceeds not waiting for the result of Intent
public void run() {
// 1. Check if Bluetooth is Enabled
if (!blue.isEnabled()) {
Intent enable_Bluetooth = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enable_Bluetooth, 1);
}
// 2. Start Bluetooth Server
try {
Server = blue.listenUsingRfcommWithServiceRecord("dhiraj",
MY_UUID);
first:
Declare the Bluetooth permission(s) in your application manifest file.
For example:
<manifest ... >
<uses-permission android:name="android.permission.BLUETOOTH" />
...
</manifest>
Setting up bluetooth:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}
Enable bluetooth:
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
Finding devices:
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// 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());
}
}
discovering devices:
// Create a BroadcastReceiver for ACTION_FOUND
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);
// 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);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
Enabling discovery
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);

Scanning for nearby bluetooth devices

If the phone has bluetooth toggled on, can an app read the list of the ids of nearby discoverable devices? If so, which function returns such a list?
Thanks!
Have a look here
// Create a BroadcastReceiver for ACTION_FOUND
private 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);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

Categories

Resources