Not able to scan bluetooth devices - android

I am developing an app which scans the bluetooth devices and list them all. My requirement is that I have to scan for devices as soon as application starts..Now my problem is when i run the app for the first time it only turns on the bluetooth but does not scan for devices..
I can see the bluetooth icon on screen but in log cat getState() method of the BluetoothAdapter shows state as STATE_OFF.
Please anyone help me about this issue ??
Here is my code snippet
public class MainActivity extends Activity {
private BluetoothAdapter bluetoothAdapter;
Set<String> BTList;
ArrayAdapter<String> BTAdapter;
private ListView listView;
private BroadcastReceiver mReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
listView = (ListView) findViewById(R.id.listView1);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null)
Toast.makeText(this, "Devices does not support Bluetooth",
Toast.LENGTH_SHORT).show();
if (!bluetoothAdapter.isEnabled())
bluetoothAdapter.enable();
if(bluetoothAdapter.isEnabled()) {
if(bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
}
bluetoothAdapter.startDiscovery();
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BTAdapter.add(device.getName() + "\n" + device.getAddress());
BTAdapter.notifyDataSetChanged();
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
BTAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_expandable_list_item_1);
listView.setAdapter(BTAdapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
//if(bluetoothAdapter != null)
// bluetoothAdapter.cancelDiscovery();
unregisterReceiver(mReceiver);
}
}

Check in your AndroidManifest.xml file, if you have these below entries
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />

Related

Bluetooth connection between a smartwatch (Wear OS) and an Arduino Nano BLE 33

I'm a student and I'm new in Android's world.
What I want to do is try to connect my smartwatch to Arduino Nano BLE 33 (because I should show Arduino's data on my smarwatch).
First of all I try to use this guide Bluetooth low energy but I failed(probably I do something wrong).
Then I read this Bluetooth overview and I tried to develope an app for smartphone (because It's more easy) and I obtained this:
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button scanButton;
ListView scanListView;
ArrayList<String> stringArrayList = new ArrayList<String>();
ArrayAdapter<String> arrayAdapter;
BluetoothAdapter myAdapter = BluetoothAdapter.getDefaultAdapter();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scanButton = (Button) findViewById(R.id.scan_button);
scanListView = (ListView) findViewById(R.id.scanned_list);
scanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myAdapter.startDiscovery();
}
});
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, intentFilter);
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,stringArrayList);
scanListView.setAdapter(arrayAdapter);
}
BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
stringArrayList.add(device.getName());
arrayAdapter.notifyDataSetChanged();
}
}
};
}
It works on my smartphone and my smartphone detects Arduino.
Now I would like to get the same with the smartwatch but I don't know to change the code.
Can someone help me??
I'm so sorry if my ask is stupid.
Considering this code for wear os:
public class MainActivity extends WearableActivity {
private TextView text;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter;
private ListView scanList;
//private ArrayList<String> stringArrayList = new ArrayList<String>();
//private ArrayAdapter<String> arrayAdapter;
private Button scanButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
scanButton = (Button) findViewById(R.id.button);
// recuperiamo un riferimento al BluetoothManager
// BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
// recuperiamo un riferimento all'adapter Bluetooth
btAdapter = BluetoothAdapter.getDefaultAdapter();
// verifichiamo che Bluetooth sia attivo nel dispositivo
if (btAdapter == null || !btAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_ENABLE_BT);
}
// premendo il bottone inizio la ricerca dei dispositivi
scanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btAdapter.startDiscovery();
text.setText("Ricerca dispositivi");
}
});
// Register for broadcasts when a device is discovered.
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
//scanList.setAdapter(arrayAdapter);
// Enables Always-on
setAmbientEnabled();
}
// Create a BroadcastReceiver for ACTION_FOUND.
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
text.setText("Ecco il dispositivo trovato");
//stringArrayList.add(device.getName()); //prendo i nomi dei device
//String deviceHardwareAddress = device.getAddress(); // MAC address
}
else
text.setText("Nessun dispositivo trovato");
}
};
}
Could It possible that registerReceiver doesn't work for WearableActivity?

How can I solve this NullPointer error in my Android app?

I've made a screen in android studio that manages some aspects of bluetooth like searching for devices, on and off and so on. The problem appeared when I ran the app, I get a NullPointer error when changing the bluetooth images from on to off and viceversa.
My code so far (simplified):
private ListView listView;
private ArrayList<String> mDeviceList = new ArrayList<>();
Button mBotOn, mBotOff,mBotDescubrir, mBotEmparejar, mBotEmp;
private BluetoothAdapter mBlueAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ajustes_conexion_sensores);
listView = findViewById(R.id.listView);
mBlueAdapter = BluetoothAdapter.getDefaultAdapter();
final IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
if (mBlueAdapter == null) {
mEstadoBlueTv.setText("Bluetooth no disponible.");
} else {
mEstadoBlueTv.setText("Bluetooth está disponible.");
}
mBotDescubrir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerReceiver(mReceiver, filter);
mBlueAdapter.startDiscovery();
}
});
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device.getName() + "\n" + device.getAddress());
listView.setAdapter(new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, mDeviceList));
}
}
};
I get the NullPointer Exception here:
if (mBlueAdapter.isEnabled()) {
mBluetIv.setImageResource(R.drawable.bt_on);
} else {
mBluetIv.setImageResource(R.drawable.bt_off);
}
The error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean
android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
at serenaApp.serenaapp.AjustesConexionSensores.onCreate(AjustesConexionSensores.java:62)
Thank your in advance
if(mBlueAdapter!=null && mBlueAdapter.isEnabled() !=null && mBluetIv!=null){
if (mBlueAdapter.isEnabled()) {
mBluetIv.setImageResource(R.drawable.bt_on);
} else {
mBluetIv.setImageResource(R.drawable.bt_off);
}
}

Detect Enable/Disable Bluetooth

I made an application to turn on/off bluetooth. To turn on/off i used a switch button. Here is the code:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private final static int REQUEST_ENABLE_BT = 1;
BluetoothAdapter mBluetoothAdapter = null;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(mBluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
switch (state){
case BluetoothAdapter.STATE_OFF:
break;
case BluetoothAdapter.STATE_ON:
break;
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Switch bluetoothSwitch = (Switch) findViewById(R.id.bluetoothSwitch);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null){
//Device does not support bluetooth
}
else{
bluetoothSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(bluetoothSwitch.isChecked() && !mBluetoothAdapter.isEnabled()){
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, BTIntent);
}
if(!bluetoothSwitch.isChecked() && mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, BTIntent);
}
}
});
}
}
}
The problem is that if i turn on/off bluetooth from settings and not from my app the switch doesn't change.
I have implemented a broadcast receiver but i can't access the switch from it.
I tried:
bluetoothSwich.setChecked(true)
inside the broadcast receiver but it doesn't work.
Ty
EDIT :
I partially solved the problem with the global switch but to catch the on/off action from settings first i have to click the on/off button from my app at least one time. any suggestion?
To detect the state change of bluetooth you need to add following permission to your AndroidManifest.xml.
<uses-permission android:name="android.permission.BLUETOOTH" />
Use a Local broadcast preferably. You do not need to register it in Manifest . register it at runtime where you need it.(If need throughout the app then register it in Manifest)
private final BroadcastReceiver bStateReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_OFF) {
// Bluetooth is disconnected, do handling here
}
}
}
};
Runtime register:
LocalBroadcastManager.getInstance(this).registerReceiver(bStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
Runtime unregister : Don't forget to unregister the broadcast.
LocalBroadcastManager.getInstance(this).unregisterReceiver(bStateReceiver);
Static Register:
<receiver
android:name=".FullyQualifiedBroadcastReceiverClassName"
android:enabled="true">
<intent-filter>
<action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>
</intent-filter>

Android code to alert when a specific bluetooth device is on

I want to know how make a Bluetooth program with android, witch the main functionality is alert me when a specific Bluetooth device is on (by introducing on code for example the name of that device).
E.g. If my cell phone Bluetooth is on i want to be alert in my android program in another cell phone for example.
I try some programs but they gave me all the same, only discover new devices or connect to them.
Thanks
mSpecificDevice is the specific device you want to check.
MainActivity.java:
public class MainActivity extends Activity {
// Return Intent extra
public static String EXTRA_DEVICE_ADDRESS = "device_address";
private String mSpecificDevice = "my-device";
// Member fields
private BluetoothAdapter mBtAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set result CANCELED in case the user backs out
setResult(Activity.RESULT_CANCELED);
// 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();
}
public void doDiscovery(View view) {
doDiscovery();
}
#Override
protected void onStart() {
super.onStart();
}
#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 we're already discovering, stop it
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
}
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 (mSpecificDevice.equals(device.getName())) {
Toast.makeText(getApplicationContext(), device.getName() + " is on", Toast.LENGTH_LONG).show();
}
}
}
};
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check"
android:onClick="doDiscovery"/>
Don't forget to add the following to AndroidManifest.xml:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
instead of button calling doDiscovery you can use threading which call this methaod after every some seconds

Dynamicly add discovered Bluetooth devices to ListPreference

I have a PreferenceFragment with the following preference xml resource:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:title="#string/Preferences">
<PreferenceCategory
android:title="#string/Bluetooth">
<CheckBoxPreference
android:key="pref_bt_enabled"
android:title="#string/Bt_checkbox"
android:summary="#string/Bt_checkbox_summary"
android:defaultValue="false" />
<ListPreference
android:key="pref_bt_devices"
android:summary="#string/Bt_devices_summary"
android:title="#string/Bt_devices"
android:enabled="false" />
</PreferenceCategory>
</PreferenceScreen>
What I'm trying to do is this:
When I enable the pref_bt_enabled, I turn on Bluetooth, look for paired devices and also discover other devices and add them all to the ListPreference. This is the code I use so far:
public class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener {
private static final int REQUEST_ENABLE_BT = 100;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> pairedDevices;
Set<BluetoothDevice> discoveredDevices;
ListPreference btDevicesList;
ArrayList<CharSequence> entries;
ArrayList<CharSequence> entryValues;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
btDevicesList = (ListPreference) findPreference("pref_bt_devices");
btAdapter = getBtAdapter();
if (btAdapter != null) {
findPreference("pref_bt_enabled").setEnabled(true);
}
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
getActivity().registerReceiver(btDiscoveryReceiver, filter);
}
#Override
public void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onDestroy() {
super.onPause();
getActivity().unregisterReceiver(btDiscoveryReceiver);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("pref_bt_enabled")) {
if (sharedPreferences.getBoolean(key, false) == true) {
enableBluetooth();
findPairedDevices();
discoverDevices();
btDevicesList.setEnabled(true);
}
else {
btAdapter.disable();
btDevicesList.setEnabled(false);
}
}
}
public BluetoothAdapter getBtAdapter() {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
return null;
}
else {
return mBluetoothAdapter;
}
}
public void enableBluetooth() {
if (!btAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
public void findPairedDevices() {
pairedDevices = btAdapter.getBondedDevices();
entries = new ArrayList<CharSequence>();
entryValues = new ArrayList<CharSequence>();
for (BluetoothDevice d : pairedDevices) {
entries.add("paired: " + d.getName());
entryValues.add(d.getAddress());
}
btDevicesList.setEntries(listToArray(entries));
btDevicesList.setEntryValues(listToArray(entryValues));
}
public void discoverDevices() {
btAdapter.startDiscovery();
}
public CharSequence[] listToArray(ArrayList<CharSequence> list) {
CharSequence[] sequence = new CharSequence[list.size()];
for (int i = 0; i < list.size(); i++) {
sequence[i] = list.get(i);
}
return sequence;
}
private final BroadcastReceiver btDiscoveryReceiver = 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);
discoveredDevices.add(device);
entries.add("discovered: " + device.getName());
btDevicesList.setEntries(listToArray(entries));
entryValues.add(device.getAddress());
btDevicesList.setEntryValues(listToArray(entryValues));
}
}
};
}
When I turn on Bluetooth using my checkbox, Bluetooth turns on, but my ListPreference remains empty even when I have a Bluetooth device nerby and It is discoverable. I get no errors running this code. Thanks for your advice!
You code is actually throwing an exception in btDiscoveryReceiver, discoveredDevices is never initialized.

Categories

Resources