Capture bluetooth upon paired state - android

I have a listViewwhich will display a list of paired bluetooth devices. I wanna capture the state inorder to update the paired listView whenever a new request to pair with my device gets accepted.
So far I have tried listening to BluetoothDevice.ACTION_ACL_CONNECTED but to no avail.
protected void onCreate(Bundle savedInstanceState) {
...
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
this.registerReceiver(mReceiver, filter1);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
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_CONNECTED.equals(action)) {
getPairedDevices(); // get paired devices and update listView
}
}

First, to scan pair and unpair device, you can you this code
public void scanDevices(){
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
activity.registerReceiver(mReceiverScan, filter);
bluetoothAdapter.startDiscovery();
}
public void pair(BluetoothDevice device){
activity.registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
devicePair=device;
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
if(discoveryCallback!=null)
discoveryCallback.onError(e.getMessage());
}
}
public void unpair(BluetoothDevice device) {
devicePair=device;
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
if(discoveryCallback!=null)
discoveryCallback.onError(e.getMessage());
}
}
private BroadcastReceiver mReceiverScan = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case BluetoothAdapter.ACTION_STATE_CHANGED:
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_OFF) {
if (discoveryCallback != null)
discoveryCallback.onError("Bluetooth turned off");
}
break;
case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
context.unregisterReceiver(mReceiverScan);
if (discoveryCallback != null)
discoveryCallback.onFinish();
break;
case BluetoothDevice.ACTION_FOUND:
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (discoveryCallback != null)
discoveryCallback.onDevice(device);
break;
}
}
};
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
if(discoveryCallback!=null)
discoveryCallback.onPair(devicePair);
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
if(discoveryCallback!=null)
discoveryCallback.onUnpair(devicePair);
}
}
}
};
Finally, you can add these device to a list as
public List<BluetoothDevice> getPairedDevices(){
List<BluetoothDevice> devices = new ArrayList<>();
for (BluetoothDevice blueDevice : bluetoothAdapter.getBondedDevices()) {
devices.add(blueDevice);
}
return devices;
}
Don't forget to add permission in AndroidManifet.xml file
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
This is a good library that I used is
https://github.com/omaflak/Bluetooth-Library
And this is a sample app to use the above lib.
https://github.com/omaflak/Bluetooth-Android

Related

Perform a bluetooth scan with BluetoothAdapter in Xamarin.android

I am implementing an APP with Xamarin.
I want to perform a Bluetooth scan. And get the device found.
Here is my code.
How could I implement this to start a scan and collect the result once"Button_Scan()" is triggered?
Thank you.
[BroadcastReceiver(Enabled = true)]
public class BluetoothReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
var action = intent.Action;
if (action != BluetoothDevice.ActionFound)
{
return;
}
if (BluetoothDevice.ActionFound.Equals(action))
{
var device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
var ConnectState = device.BondState;
/*
switch (ConnectState)
{
case Bond.None:
break;
case Bond.Bonded:
break;
case Bond.Bonding:
break;
}
*/
if (device.Name != null)
{
Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Found device", device.Name, "ok");
}
}
}
}
public async void Button_Scan(object sender, EventArgs e)
{
try
{
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;
mBluetoothAdapter.Enable();
mBluetoothAdapter.StartDiscovery();
}
catch(Exception ex)
{
DisplayAlert("ex", ex.ToString(), "ok");
}
}
You have defined a BluetoothReceiver to receive the result ,you just add the device information into a deviceList.
public static List<string> mDeviceList = new List<string>();
public override void OnReceive(Context context, Intent intent)
{
string action = intent.Action;
if (BluetoothDevice.ActionFound.Equals(action))
{
BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
mDeviceList.Add(device.Name + ";" + device.Address);
}
}
Don't forget to regist the broadcast.
BluetoothReceiverreceiver = new BluetoothReceiver();
IntentFilter filter = new IntentFilter(BluetoothDevice.ActionFound);
RegisterReceiver(receiver, filter);

Connection between android device and bluetooth headsets programatically

How can i make an app in android that can provide connection between the android device and the bluetooth speakers.
How to pair:
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
How to Unpair:
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
The receiver to catch the pairing process:
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
showToast("Paired");
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
showToast("Unpaired");
}
}
}
};
Register receiver:
IntentFilter intent = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mPairReceiver, intent);

Bluetooth App crashes on launch

I am an absolute beginner in android development. I tried making a Bluetooth app
and it crashes on launch. The app is supposed to search and connect to a specific device whose name is entered by the user. I've caught every exception but I am clueless. Any help would be appreciated. The Complete code is attached.
Thanks.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.bluetooth.*;
import android.widget.*;
import android.util.*;
import android.content.*;
import android.view.View;
import java.io.*;
import java.util.*;
public class MainActivity extends AppCompatActivity {
public BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
UUID newUUID = UUID.randomUUID();
InputStream inStream;
byte[] buffer = new byte[1024];
public ArrayList<BluetoothDevice> devices = new ArrayList<>();
public TextView text = findViewById(R.id.textView);
public String incomingMessage;
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
Log.d("", "onReceive: STATE OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d("", "mBroadcastReceiver1: STATE TURNING OFF");
break;
case BluetoothAdapter.STATE_ON:
Log.d("", "mBroadcastReceiver1: STATE ON");
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d("", "mBroadcastReceiver1: STATE TURNING ON");
break;
}
}
}
};
private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothAdapter.ACTION_SCAN_MODE_CHANGED.equals(action)) {
int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
switch (mode) {
//Device is in Discoverable Mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Log.d("", "mBroadcastReceiver2: Discoverability Enabled.");
break;
//Device not in discoverable mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Log.d("", "mBroadcastReceiver2: Discoverability Disabled. Able to receive connections.");
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Log.d("", "mBroadcastReceiver2: Discoverability Disabled. Not able to receive connections.");
break;
case BluetoothAdapter.STATE_CONNECTING:
Log.d("", "mBroadcastReceiver2: Connecting....");
break;
case BluetoothAdapter.STATE_CONNECTED:
Log.d("", "mBroadcastReceiver2: Connected.");
break;
}
}
}
};
private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d("", "onReceive: ACTION FOUND.");
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
Log.d("", "onReceive: " + device.getName() + ": " + device.getAddress());
}
}
};
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
Log.d("", "BroadcastReceiver: BOND_BONDED.");
}
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d("", "BroadcastReceiver: BOND_BONDING.");
}
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
Log.d("", "BroadcastReceiver: BOND_NONE.");
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onCLick(View button) {
IntentFilter m4 = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBroadcastReceiver4,m4);
if(adapter==null)
{
Log.d("","Bluetooth is null");
onDestroy();
}
EditText deviceName = findViewById(R.id.editText);
String name = deviceName.getText().toString();
BluetoothDevice targetDevice = null;
if (!adapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, 1);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1,BTIntent);
Toast.makeText(getApplicationContext(),"BT TURNED ON",Toast.LENGTH_LONG).show();
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadcastReceiver2,intentFilter);
}
Set<BluetoothDevice> paired_devices = adapter.getBondedDevices();
Toast.makeText(getApplicationContext(),"GETTING BONDED DEVICES",Toast.LENGTH_LONG).show();
if (paired_devices.size() > 0) {
for (BluetoothDevice mdevice : paired_devices) {
if (mdevice.getName().equals("name")) {
Toast.makeText(getApplicationContext(),"FOUND DEVICE",Toast.LENGTH_LONG).show();
targetDevice = mdevice;
break;
}
}
}
else
{
Toast.makeText(getApplicationContext(),"SEARCHING DEVICES",Toast.LENGTH_LONG).show();
if(adapter.isDiscovering())
adapter.cancelDiscovery();
adapter.startDiscovery();
IntentFilter deviceFound = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3,deviceFound);
for(BluetoothDevice mdevice:devices)
{
if(name.equalsIgnoreCase(mdevice.getName()))
{
targetDevice = mdevice;
}
}
if(devices.size()==0)
{
Toast.makeText(getApplicationContext(),"NO DEVICE FOUND... QUITTING",Toast.LENGTH_LONG).show();
}
}
BluetoothSocket mSocket = null;
try {
assert targetDevice != null;
mSocket = targetDevice.createInsecureRfcommSocketToServiceRecord(newUUID);
} catch (IOException | AssertionError e) {
Toast.makeText(getApplicationContext(),"COULD NOT BE CONNECTED",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
try {
assert mSocket != null;
mSocket.connect();
} catch (IOException|AssertionError e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"COULD NOT MAKE CONNECTION",Toast.LENGTH_LONG).show();
}
try {
assert mSocket != null;
inStream = mSocket.getInputStream();
} catch (IOException|AssertionError | NullPointerException e) {
Toast.makeText(getApplicationContext(),"PROBLEM CONNECTING",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
while(true)
{
try {
int bytes = inStream.read(buffer);
incomingMessage = new String(buffer,0,bytes);
} catch (IOException e) {
e.printStackTrace();
break;
}
}
text.setText(incomingMessage);
Toast.makeText(getApplicationContext(),"END OF PROGRAM",Toast.LENGTH_LONG).show();
}
}
[ https://i.stack.imgur.com/3v3qI.png]
[ https://i.stack.imgur.com/42Ge5.png ]
Second link for logcat crash after button press
You can not find a view by id, until it is rendered. If you write findViewById at global level, then activity tries to load that View before setting layout.
Put your findViewById code after setContentView().
package in.ks.widgetClock.defaultClasses.webservice;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.bluetooth.*;
import android.widget.*;
import android.util.*;
import android.content.*;
import android.view.View;
import java.io.*;
import java.util.*;
import in.ks.widgetClock.R;
public class MainActivity extends AppCompatActivity {
public BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
UUID newUUID = UUID.randomUUID();
InputStream inStream;
byte[] buffer = new byte[1024];
public ArrayList<BluetoothDevice> devices = new ArrayList<>();
public TextView text;
public String incomingMessage;
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
Log.d("", "onReceive: STATE OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d("", "mBroadcastReceiver1: STATE TURNING OFF");
break;
case BluetoothAdapter.STATE_ON:
Log.d("", "mBroadcastReceiver1: STATE ON");
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d("", "mBroadcastReceiver1: STATE TURNING ON");
break;
}
}
}
};
private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothAdapter.ACTION_SCAN_MODE_CHANGED.equals(action)) {
int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
switch (mode) {
//Device is in Discoverable Mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Log.d("", "mBroadcastReceiver2: Discoverability Enabled.");
break;
//Device not in discoverable mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Log.d("", "mBroadcastReceiver2: Discoverability Disabled. Able to receive connections.");
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Log.d("", "mBroadcastReceiver2: Discoverability Disabled. Not able to receive connections.");
break;
case BluetoothAdapter.STATE_CONNECTING:
Log.d("", "mBroadcastReceiver2: Connecting....");
break;
case BluetoothAdapter.STATE_CONNECTED:
Log.d("", "mBroadcastReceiver2: Connected.");
break;
}
}
}
};
private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d("", "onReceive: ACTION FOUND.");
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
Log.d("", "onReceive: " + device.getName() + ": " + device.getAddress());
}
}
};
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
Log.d("", "BroadcastReceiver: BOND_BONDED.");
}
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d("", "BroadcastReceiver: BOND_BONDING.");
}
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
Log.d("", "BroadcastReceiver: BOND_NONE.");
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.textView);
}
public void onCLick(View button) {
IntentFilter m4 = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBroadcastReceiver4,m4);
if(adapter==null)
{
Log.d("","Bluetooth is null");
onDestroy();
}
EditText deviceName = findViewById(R.id.editText);
String name = deviceName.getText().toString();
BluetoothDevice targetDevice = null;
if (!adapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, 1);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1,BTIntent);
Toast.makeText(getApplicationContext(),"BT TURNED ON",Toast.LENGTH_LONG).show();
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadcastReceiver2,intentFilter);
}
Set<BluetoothDevice> paired_devices = adapter.getBondedDevices();
Toast.makeText(getApplicationContext(),"GETTING BONDED DEVICES",Toast.LENGTH_LONG).show();
if (paired_devices.size() > 0) {
for (BluetoothDevice mdevice : paired_devices) {
if (mdevice.getName().equals("name")) {
Toast.makeText(getApplicationContext(),"FOUND DEVICE",Toast.LENGTH_LONG).show();
targetDevice = mdevice;
break;
}
}
}
else
{
Toast.makeText(getApplicationContext(),"SEARCHING DEVICES",Toast.LENGTH_LONG).show();
if(adapter.isDiscovering())
adapter.cancelDiscovery();
adapter.startDiscovery();
IntentFilter deviceFound = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3,deviceFound);
for(BluetoothDevice mdevice:devices)
{
if(name.equalsIgnoreCase(mdevice.getName()))
{
targetDevice = mdevice;
}
}
if(devices.size()==0)
{
Toast.makeText(getApplicationContext(),"NO DEVICE FOUND... QUITTING",Toast.LENGTH_LONG).show();
}
}
BluetoothSocket mSocket = null;
try {
assert targetDevice != null;
mSocket = targetDevice.createInsecureRfcommSocketToServiceRecord(newUUID);
} catch (IOException | AssertionError e) {
Toast.makeText(getApplicationContext(),"COULD NOT BE CONNECTED",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
try {
assert mSocket != null;
mSocket.connect();
} catch (IOException|AssertionError e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"COULD NOT MAKE CONNECTION",Toast.LENGTH_LONG).show();
}
try {
assert mSocket != null;
inStream = mSocket.getInputStream();
} catch (IOException|AssertionError | NullPointerException e) {
Toast.makeText(getApplicationContext(),"PROBLEM CONNECTING",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
while(true)
{
try {
int bytes = inStream.read(buffer);
incomingMessage = new String(buffer,0,bytes);
} catch (IOException e) {
e.printStackTrace();
break;
}
}
text.setText(incomingMessage);
Toast.makeText(getApplicationContext(),"END OF PROGRAM",Toast.LENGTH_LONG).show();
}
}

Bluetooth Connection

I've looked at quite a lot of topics on this in different forums and none seem to help me.
I recently bought an Elegoo car kit, which is compatible with the Arduino IDE, and it comes with different types of code and what not. they even have their own Android app.
My problem is I want to create my own android Bluetooth application that connects/pairs with the module and can control the car remotely. I have my application up and running, it can scan for nearby devices and the HC-08 module appears in the list but I am not able to connect. when I try to connect it says it can't communicate with HC-08. I am pretty sure the problem lies in the android end as the elegoo Bluetooth app connects no problem at all with the Bluetooth module if there is any code on the elegoo board or not. The bluetooth module is a HC-08.
Can someone help me with this ?
Also I am following this youtube tutorial so the credit goes to him for the code.
https://www.youtube.com/watch?v=YJ0JQXcNNTA
Here is the main activity code:
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemClickListener{
private static final String TAG = "MainActivity";
BluetoothAdapter mBluetoothAdapter;
Button btnEnableDisable_Discoverable;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
ListView lvNewDevices;
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
switch(state){
case BluetoothAdapter.STATE_OFF:
Log.d(TAG, "onReceive: STATE OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING OFF");
break;
case BluetoothAdapter.STATE_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE ON");
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING ON");
break;
}
}
}
};
/**
* Broadcast Receiver for changes made to bluetooth states such as:
* 1) Discoverability mode on/off or expire.
*/
private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {
int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
switch (mode) {
//Device is in Discoverable Mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Enabled.");
break;
//Device not in discoverable mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Able to receive connections.");
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Not able to receive connections.");
break;
case BluetoothAdapter.STATE_CONNECTING:
Log.d(TAG, "mBroadcastReceiver2: Connecting....");
break;
case BluetoothAdapter.STATE_CONNECTED:
Log.d(TAG, "mBroadcastReceiver2: Connected.");
break;
}
}
}
};
/**
* Broadcast Receiver for listing devices that are not yet paired
* -Executed by btnDiscover() method.
*/
private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "onReceive: ACTION FOUND.");
if (action.equals(BluetoothDevice.ACTION_FOUND)){
BluetoothDevice device = intent.getParcelableExtra (BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
lvNewDevices.setAdapter(mDeviceListAdapter);
}
}
};
/**
* Broadcast Receiver that detects bond state changes (Pairing status changes)
*/
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//3 cases:
//case1: bonded already
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){
Log.d(TAG, "BroadcastReceiver: BOND_BONDED.");
}
//case2: creating a bone
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
}
//case3: breaking a bond
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
}
}
}
};
#Override
protected void onDestroy() {
Log.d(TAG, "onDestroy: called.");
super.onDestroy();
unregisterReceiver(mBroadcastReceiver1);
unregisterReceiver(mBroadcastReceiver2);
unregisterReceiver(mBroadcastReceiver3);
unregisterReceiver(mBroadcastReceiver4);
//mBluetoothAdapter.cancelDiscovery();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnONOFF = (Button) findViewById(R.id.btnONOFF);
btnEnableDisable_Discoverable = (Button) findViewById(R.id.btnDiscoverable_on_off);
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
mBTDevices = new ArrayList<>();
//Broadcasts when bond state changes (ie:pairing)
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBroadcastReceiver4, filter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
lvNewDevices.setOnItemClickListener(MainActivity.this);
btnONOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: enabling/disabling bluetooth.");
enableDisableBT();
}
});
}
public void enableDisableBT(){
if(mBluetoothAdapter == null){
Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");
}
if(!mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: enabling BT.");
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTIntent);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
if(mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: disabling BT.");
mBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
}
public void btnEnableDisable_Discoverable(View view) {
Log.d(TAG, "btnEnableDisable_Discoverable: Making device discoverable for 300 seconds.");
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadcastReceiver2,intentFilter);
}
public void btnDiscover(View view) {
Log.d(TAG, "btnDiscover: Looking for unpaired devices.");
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "btnDiscover: Canceling discovery.");
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if(!mBluetoothAdapter.isDiscovering()){
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
}
/**
* This method is required for all devices running API23+
* Android must programmatically check the permissions for bluetooth. Putting the proper permissions
* in the manifest is not enough.
*
* NOTE: This will only execute on versions > LOLLIPOP because it is not needed otherwise.
*/
private void checkBTPermissions() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}
}else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//first cancel discovery because its very memory intensive.
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "onItemClick: You Clicked on a device.");
String deviceName = mBTDevices.get(i).getName();
String deviceAddress = mBTDevices.get(i).getAddress();
Log.d(TAG, "onItemClick: deviceName = " + deviceName);
Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);
//create the bond.
//NOTE: Requires API 17+? I think this is JellyBean
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
Log.d(TAG, "Trying to pair with " + deviceName);
mBTDevices.get(i).createBond();
}
}
}
/// Here is also my DeviceListAdapter code:
public class DeviceListAdapter extends ArrayAdapter<BluetoothDevice> {
private LayoutInflater mLayoutInflater;
private ArrayList<BluetoothDevice> mDevices;
private int mViewResourceId;
public DeviceListAdapter(Context context, int tvResourceId, ArrayList<BluetoothDevice> devices){
super(context, tvResourceId,devices);
this.mDevices = devices;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mViewResourceId = tvResourceId;
}
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mLayoutInflater.inflate(mViewResourceId, null);
BluetoothDevice device = mDevices.get(position);
if (device != null) {
TextView deviceName = (TextView) convertView.findViewById(R.id.tvDeviceName);
TextView deviceAdress = (TextView) convertView.findViewById(R.id.tvDeviceAddress);
if (deviceName != null) {
deviceName.setText(device.getName());
}
if (deviceAdress != null) {
deviceAdress.setText(device.getAddress());
}
}
return convertView;
}
}
Some of the tutorials on Bluetooth are pretty old! I just got Arduino-Android Bluetooth communication working last week so this should work for you! First in your manifest file add these permissions:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Then use this in your main.
public class MainActivity extends AppCompatActivity {
private final String DEVICE_ADDRESS="benamekhoda"; //I actually used Device Name instead of address
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Serial Port Service UUID
private BluetoothDevice device; //Our Bluetooth Device
private BluetoothSocket socket;
private OutputStream outputStream;
private InputStream inputStream;
Button startButton, sendButton,clearButton,stopButton;
TextView textView;
EditText editText;
boolean deviceConnected=false;
Thread thread;
byte buffer[];
int bufferPosition;
boolean stopThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.edittext);
textView = (TextView) findViewById(R.id.textview);
startButton = (Button) findViewById(R.id.buttonStart);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(BTinit())
{
if(BTconnect())
{
setUiEnabled(true);
deviceConnected=true;
beginListenForData();
textView.append("\nConnection Opened!\n");
}
else{
Toast.makeText(getApplicationContext(),"BTconnect false",Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(getApplicationContext(),"BTinit false",Toast.LENGTH_SHORT).show();
}
}
});
sendButton = (Button) findViewById(R.id.buttonSend);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String string = editText.getText().toString();
string.concat("\n");
try {
outputStream.write(string.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
textView.append("\nSent Data:"+string+"\n");
}
});
clearButton = (Button) findViewById(R.id.buttonClear);
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onClickClear(view);
}
});
stopButton = (Button) findViewById(R.id.buttonStop);
stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onClickSend(view);
}
});
setUiEnabled(false);
}
public void setUiEnabled(boolean bool)
{
startButton.setEnabled(!bool);
sendButton.setEnabled(bool);
stopButton.setEnabled(bool);
textView.setEnabled(bool);
}
public boolean BTinit()
{
boolean found=false;
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
}
if(!bluetoothAdapter.isEnabled())
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices(); //Something like ArrayList but no duplicate is allowed and data is unordered
if(bondedDevices.isEmpty())
{
Toast.makeText(getApplicationContext(),"Please Pair the Device first",Toast.LENGTH_SHORT).show();
}
else
{
for (BluetoothDevice iterator : bondedDevices)
{
if(iterator.getName().equals(DEVICE_ADDRESS))
{
device=iterator;
Toast.makeText(getApplicationContext(),"found the device",Toast.LENGTH_SHORT).show();
found=true;
break;
}
}
}
return found;
}
public boolean BTconnect()
{
boolean connected=true;
try {
socket = device.createRfcommSocketToServiceRecord(PORT_UUID);
socket.connect();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"throw1",Toast.LENGTH_SHORT).show();
connected=false;
}
if(connected)
{
try {
outputStream=socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"throw2",Toast.LENGTH_SHORT).show();
}
try {
inputStream=socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"throw3",Toast.LENGTH_SHORT).show();
}
}
return connected;
}
void beginListenForData()
{
final Handler handler = new Handler();
stopThread = false;
buffer = new byte[1024];
Thread thread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopThread)
{
try
{
int byteCount = inputStream.available();
if(byteCount > 0)
{
byte[] rawBytes = new byte[byteCount];
inputStream.read(rawBytes);
final String string=new String(rawBytes,"UTF-8");
handler.post(new Runnable() {
public void run()
{
textView.append(string);
}
});
}
}
catch (IOException ex)
{
stopThread = true;
Toast.makeText(getApplicationContext(),"throw4",Toast.LENGTH_SHORT).show();
}
}
}
});
thread.start();
}
public void onClickSend(View view) {
String string = editText.getText().toString();
string.concat("\n");
try {
outputStream.write(string.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
textView.append("\nSent Data:"+string+"\n");
}
public void onClickStop(View view) throws IOException {
stopThread = true;
outputStream.close();
inputStream.close();
socket.close();
setUiEnabled(false);
deviceConnected=false;
textView.append("\nConnection Closed!\n");
}
public void onClickClear(View view) {
textView.setText("");
}
}
I got it from this awesome tutorial by Hariharan Mathavan from All About Circuits.

how to detect bluetooth scanner connected to Android

I want to find if bluetooth scanner is connected to my android mobile or not after every 7 seconds. For that I created a receiver where I found the bondeddevices and then its majorclass. But its not working not finding any device. What might be the problem?
Here's the Activity class:
public class Activity_Home extends ActionBarActivity implements
OnClickListener {
CountDownTimer wifiTimer, timer;
BluetoothAdapter mBluetoothAdapter;
BluetoothDevice bluetoothDevice;
CheckBluetoothScanner mReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReceiver = new CheckBluetoothScanner();
isScannerConnected();
}
private void isScannerConnected() {
timer = new CountDownTimer(Long.MAX_VALUE, 7000) { // -------call
// amethod
// after
// certain
// time
// interval-------
// This is called every interval. (Every 7 seconds in this example)
public void onTick(long millisUntilFinished) {
Log.d("test", "Timer tick");
System.out.println("=======bluetooth--start");
try {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()) {
IntentFilter filter = new IntentFilter(
BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
mBluetoothAdapter.startDiscovery();
System.out.println("============utility: "
+ Utility.SCANNER_ON);
if (Utility.SCANNER_ON.equalsIgnoreCase("true")) {
tv_scanner
.setBackgroundResource(R.drawable.scanner);
} else {
tv_scanner.setBackgroundResource(0);
}
} else {
tv_scanner.setBackgroundResource(0);
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void onFinish() {
Log.d("test", "Timer last tick");
timer.cancel();
}
}.start();
}
Here's the receiver class:
public class CheckBluetoothScanner extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
}
else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Set pairedDevices = BluetoothAdapter.getDefaultAdapter()
.getBondedDevices();
BluetoothDevice device1 = null;
for (Object item : pairedDevices) {
device1 = (BluetoothDevice) item;
}
BluetoothClass bluetoothClass = device1.getBluetoothClass();
System.out.println("======bluetoothClass"+bluetoothClass);
if (bluetoothClass != null) {
int deviceClass = bluetoothClass.getDeviceClass();
System.out.println("=======deviceclass:"+deviceClass);
if (deviceClass == Device.Major.IMAGING
|| deviceClass == Device.Major.PERIPHERAL) {
Utility.SCANNER_ON = "true";
} else {
Utility.SCANNER_ON = "false";
}
}
}
}
};

Categories

Resources