Android Bluetooth enable - android

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

Related

How to open application using paired bluetooth device's data in broadcast Receiver

My application is use obd scanner(which is provide bluetooth interface) for get car data. I want to add one feature in this application which is app should be open itself whenever car's obd(already paired) in range of mobile's bluetooth.
My thoughts for implementing this are getting list of paired device in broadcast receiver if any of pair device contain sub-string obd(small or capital)then app should open itself.
what I had achieved :
whenever any bluetooth device which contain obd Sub string is connected with my mobile my app is open itself.process of connection is manually done by me by device setting.
code inside broadcast for above mentioned result:
public class BrodcastBlueTooth extends BroadcastReceiver {
public BrodcastBlueTooth() {
}
#Override
public void onReceive(Context context, Intent intent) {
String DeviceName=null;
String action = intent.getAction();
// Log.d("BroadcastActions", "Action "+action+"received");
int state;
BluetoothDevice bluetoothDevice;
switch(action)
{
case BluetoothDevice.ACTION_ACL_CONNECTED:
bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(context, "Connected to "+bluetoothDevice.getName(), Toast.LENGTH_SHORT).show();
Log.d("BroadcastActions", "Connected to "+bluetoothDevice.getName());
DeviceName=bluetoothDevice.getName();
if (DeviceName.contains("OBD")){
Intent newIntent = new Intent();
newIntent.setClassName("com.quad14.obdnewtry", "com.quad14.obdnewtry.activity.MainActivity");
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(newIntent);
}else if(DeviceName.contains("obd")){
Intent newIntent = new Intent();
newIntent.setClassName("com.quad14.obdnewtry", "com.quad14.obdnewtry.activity.MainActivity");
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(newIntent);
}
break;
case BluetoothDevice.ACTION_ACL_DISCONNECTED:
bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Toast.makeText(context, "Disconnected from "+bluetoothDevice.getName(),
// Toast.LENGTH_SHORT).show();
break;
}
I am declaring my broadcast in manifest so it's always working in background.
I got the paired device list by below code:
public void PairedDevice(){
Set<BluetoothDevice> pairedDevices = BTAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
PaiedDevices.add(device.getName());
Log.e("DeviceName", String.valueOf(PaiedDevices));
PairDeviceFlag=true;
}
}
}
what should i do from this point to get desired result. any other ways also welcome.

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.

Discovering available bluetooth devices in 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

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