I've build an android app which has to scans for Bluetooth devices every 15 minutes for a duration of 15 seconds. I expect my schedulejob to be triggered every 15 minutes (the minimum allowed time by android 7+), get a recent geolocation, scan for 15 seconds, and then send that list of devices with that specific geolocation to my backend. This procedure should also run even if the phone is in standby mode.
I've added logging to every step in the process to see what's actually being triggered and what not. My scheduleJob is actually running every 15 minutes as expected, but the scanning for BLE devices isn't being done. No error messages are displayed, but I can clearly see the scan process just isn't running.
To setup some tests, I've added a manual trigger to scan for devices and run the full process, when I do this, everything works as expected. So I think I can state that my setup to confirm permissions is done correctly and my location helper class is working properly (I confirmed this during the schedulejob process as well, I have successfully gotten a good location). I can confirm that the bluetooth system on my phone is working properly as the manual trigger does find my devices.
So it just seems like the startScan isn't running as I'd expect during the schedulejob. I've tested this on an Android 6, Android 7 and an Android 10, on the android 6 the scan does seem to work as expected even in standby modes, from the Android 7 onwards it doesn't work in standby mode anymore.
When the user keeps the app open and active for 15 minutes, the startscan does seem to trigger on the android 10.
For my scheduleJob I'm calling following method:
public void scheduleJob(){
ComponentName componentName = new ComponentName(this, AppService.class);
JobInfo info = new JobInfo.Builder(123, componentName)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
// 1000 * 60 * 2.5 => 2.5 minutes => Android will change this automatically to the minimum allowed => 15 minutes
.setPeriodic(2500 * 60)
.build();
}
For my permissions I have following:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
As for my startLeScan function, which I can confirm is being triggered
private void init() {
if(mMapBleScanCallback == null) {
mMapBleScanCallback = new ConcurrentSkipListMap<>();
}
if(mHandler == null) {
mHandler = new Handler();
}
if(mBluetoothAdapter == null) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
if(mBluetoothLeScanner == null) {
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
if(mScanSettingsBuilder == null) {
mScanSettingsBuilder = new ScanSettings.Builder();
mScanSettingsBuilder.setScanMode(ScanSettings.SCAN_MODE_BALANCED);
}
}
public void startLeScan() {
Log.d(TAG, "startLeScan");
if(mBluetoothLeScanner == null) {
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
if(mBluetoothLeScanner != null && !mIsScanning) {
mIsScanning = true;
notifyCallback(Constants.BLE.CALLBACK_SCAN_START, null);
//mBluetoothLeScanner.startScan(getScanFilters(), mScanSettingsBuilder.build(), mScanCallback);
// I've set my filter to null
// my scansettings are set to ScanSettings.SCAN_MODE_BALANCED during init
mBluetoothLeScanner.startScan(null, mScanSettingsBuilder.build(), mScanCallback); // I've set my filters to null
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
stopLeScan();
}
}, Constants.BLE.SCAN_PERIOD);
}
}
As for my callback, I've added logging when a device is detected. I can see in my logging during manual scan that devices are found, but not during the schedulejob, none are shown...
private ScanCallback mScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
Log.d(TAG, "onScanResult: " + result.toString());
super.onScanResult(callbackType, result);
prepareScanResult(result);
}
#Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Log.d(TAG, "onScanFailed: errorcode: " + errorCode);
}
};
Here is an image of some of the logging:
I found an article (ref. to point 1) which mentions that Samsung phones with Android 7+ don't allow scanning without a minimum of 1 scanfilter. And indeed, after implementing at least one scanfilter, everything started to work properly.
Related
I developed an App which contain ble function. And this app operated well on my development phone. But when I use this app on Samsung galaxy S10e, bluetooth is not working. And I found BluetoothLeScanner is not called. My development phone is galaxy S8 and its Version is Android 9.0(Pie), API 28. And another low version development phone(like galaxy 5, galaxy note 4) operated well too.
But galaxy S10e is same OS with galaxy S8(Android 9.0 Pie, API 28). I wonder why the app is not operate well on galaxy S10e.
I declared permission like that
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
And BluetoothLeScanenr is called here.
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public boolean BleDeviceScan(boolean enable)
{
logD(TAG, "BleDeviceScan ( " + enable + " )");
if(mBluetoothAdapter == null)
{
return false;
}
logD(TAG, "mBluetoothAdapter : " + mBluetoothAdapter.toString());
if(mBluetoothAdapter.isEnabled())
{
if (enable)
{
Log.d(TAG, "BleDeviceScan Build.VERSION.SDK_INT < MIN_SDK_INT - ELSE");
timerFlag = true;
timer = new Timer();
bleTimer();
mLEScanner.startScan(filters, settings, mScanCallback);
mListener.bleScanStart();
}
else
{
deviceShowCount = 0;
timerFlag = false;
bHandler.obtainMessage(1).sendToTarget();
mLEScanner.stopScan(mScanCallback);
mListener.bleScanStop();
}
logD(TAG, "BleDeviceScan Fin");
return true;
}
return false;
}
this function is not called in galaxy S10e.
mLEScanner.startScan(filters, settings, mScanCallback);
Should I declare something to use BluetoothLeScanner on galaxy S10e? What is the problem?
Based on your description, scanning does not start because mBluetoothAdapter.isEnabled() always returns false. Can you verify that is the case?
If the above is true, do settings on the device say that Bluetooth is turned on? If so, can detect BLE devices with an off the shelf app like LightBlue or BeaconScope?
I need to connect to a device via wi-fi and I am using WifiManager.startScan() for this. In theory onReceive() should be called back, but this doesn't happen. The code just keeps waiting for the callback.
The thing is that this code actually works fine on a Samsung tablet with Android 8.1, but it doesn't on any phones that I have tried (Huawei Android 8.0 and Samsung Android 9).
Here is the relevant code:
public void Init()
{
try {
mainWifiObj = (WifiManager) act.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiScanReceiver wifiReceiver = new WifiScanReceiver(act, logger, mainWifiObj);
act.getApplicationContext().registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mainWifiObj.startScan();
}
catch (Exception ex)
{
...
}
}
public class WifiScanReceiver extends BroadcastReceiver {
...
public void onReceive(Context c, Intent intent) {
try {
...// doesn't get here
}
} catch (Exception e) {
...
}
...
}
And here are the all important manifest permissions I used:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
The code doesn't generate any errors, it just silently fails to perform the callback.
Yes I found the answer. For a reason logical only to Android designers, you must enable Location Based Services for it to work. So it's not enough to give all the needed permissions to your app, but also go to settings and enable LBS.
The reason why it worked on the tablet is that LBS were enabled on it...but how is one supposed to keep all these dependencies under control?
Another thing to check is that you're not registering the broadcast receiver using
LocalBroadcastManager.getInstance(mContext).registerReceiver(broadcastReceiver, intentFilter);
use:
mContext.registerReceiver(broadcastReceiver, intentFilter);
I am using MI note 4(Android 7.0) and Moto x play (Android 7.1.1)
I am doing BLE scan in sperate service.
While scanning I am getting scan response as "scan failed"
Turning ON/OFF Bluetooth is not affecting in scan response.
Turning ON/OFF Wifi is also not affecting in scan response.
(But in this case android inbuilt(from Settings->Bluetooth) Bluetooth scanning was working fine).
I used BLE scanner app also but that app is also not detecting BLE advertisement!
I tried with Turn ON/OFF airplane mode with this and my device is able to scan without fail.
Scan Function:
mLeScanner.startScan(filters, scanSettings, mScanCallback);
ScanCallback:
ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
Log.e("TAG","onScanResult");
}
#Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Log.e("TAG","onScanFailed");
}
}
ScanSettings:
scanSettings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
filters:
List<ScanFilter> filters = new ArrayList<>();
ScanFilter filter = new ScanFilter.Builder().setDeviceAddress("device address").build();
filters.add(filter);
Beacon Scan filter
ScanFilter.Builder builder = new ScanFilter.Builder();
builder.setManufacturerData(0x004c, new byte[]{});
Anyone have an idea why it only worked with switching airplane mode?
will network affect for BLE scanning?
The error code 0x02 means SCAN_FAILED_APPLICATION_REGISTRATION_FAILED(Fails to start scan as app cannot be registered). This means, before moving to scan we need to initialize Bluetooth adapter
/**
* Initialize BluetoothAdapter
* Check the device has the hardware feature BLE
* Then enable the hardware,
*/
public boolean init(Context context) {
BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
return mBluetoothAdapter != null && context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
}
Then register receiver
**
* Register GATT update receiver
*/
private void registerServiceReceiver() {
this.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
registerReceiver(mReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
}
The service initialization method also including in the answer. The Service creation is optional.
/**
* Initialize Bluetooth service.
*/
public void initBLEService(Context context) {
try {
this.mContext = context;
if (mBLEService == null) {
Intent gattServiceIntent = new Intent(mContext, BLEService.class);
if (this.mContext != null) {
isBind = mContext.bindService(gattServiceIntent, mServiceConnection, mContext.BIND_AUTO_CREATE);
}
}
} catch (Exception e) {
AppLog.logError(TAG, e.getMessage());
}
}
I hope you have already added permission in the manifest given below
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-feature
android:name="android.hardware.bluetooth_le"
android:required="true" />
I hope this will help you.
My issue was resolved after user permission ACCESS_COARSE_LOCATION is granted. You could ask user permission in onStart()
Java Syntax
if (ContextCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSIONS_REQUEST_LOCATION);
}
Kotlin syntax
if (ContextCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
PERMISSIONS_REQUEST_LOCATION)
}
I'm trying to use the function BluatoothLeScanner.startScan instead of the deprecated one BluetoothAdapter.startLeScan.
Yesterday I updated my Nexus 5 to Android 6.0 and since that moment my app does not work anymore.
I firstly add the preferences required ACCESS_COARSE_LOCATION as found here, https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-hardware-id.
Then I added the permission as described here: https://developer.android.com/training/permissions/requesting.html.
But at the end it seems not working, it does not send back the ble devices.
This is my code:
manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.stm.sensitronapp">
<uses-sdk android:maxSdkVersion="23"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>`
DeviceScanActivity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_COARSE);
}
}
// Device scan callback.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
mLeDeviceListAdapter.addDevice(result.getDevice());
mLeDeviceListAdapter.notifyDataSetChanged();
}
};
}
}
}
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
if (mBluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
mSwipeRefreshLayout.setRefreshing(true);
mLeDeviceListAdapter.clear();
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION ) == PackageManager.PERMISSION_GRANTED) {
mBluetoothLeScanner.startScan(mScanCallback);
}
}
EDIT: to solve this problem I only turned on the GPS. It is easy to do it programmatically in this way.
if permissions granted, have a try: turn ON the GPS.
Is you app prompting for Location permission on startup? If it's not, handle the code somewhere else so that it is being prompted.
Also you can check this to test if your app is working fine:
Open Settings > Apps > YourApplication > Permissions
and enable Location and then try to scan for results.
Location will be listed under permissions only if you have provided ACCESS_COARSE_LOCATION on manifest.
Using the solutions provided above works but the side effect is that you have to have location services turned on for something that doesn't need it. An ugly and unsatisfying work around is to specify the target version in your manifest to
android:targetSdkVersion="21"
It allows scanning on my Nexus 7 even though the installed version is 6.0.1. I do not know what the side effects are of targeting a lower version than the installed version but at least scanning works. Might be the only solution for GPS-less devices (if such devices exist).
Google should be crucified for this.
One - not perfect answer, is that you can still use the same old method BT scan method, once you have the new runtime Location permission enabled.
mBluetoothAdapter.startDiscovery();
.......
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
}
}
};
It's an old question, but I will answer to help someone.
Unfortunately, the combination of ACCESS_COARSE_LOCATION and targetSdkVersion 22 does not work on some devices.This is not a good method, but I have solved it in the following way without using runtime permissions (ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION)
Set your 'targetSdkVersion' to 19 (I think maybe api19 ~ api22 will be possible)
Add the following permission to your manifest file
<uses-permission android:name="android.permission.READ_OWNER_DATA" />
<uses-permission android:name="android.permission.WRITE_OWNER_DATA" />
tested to Android 4.4 ~ 7.1.1
Set your 'minSdkVersion' to 18
targetSdkVersion 22
I have spent the last couple of days trying to make an app that keeps my Samsung Galaxy S3 mini (Android 2.1.4) discoverable for an "infinite" amount of time. My code looks currently as follows:
package com.example.downtoone;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;
import com.example.downtoone.*;
import android.bluetooth.*;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
public class MainActivity extends Activity {
private BluetoothAdapter mBluetoothAdapter = null;
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
private static final int REQUEST_ENABLE_DSC = 3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
#Override
public void onStart() {
super.onStart();
if (!mBluetoothAdapter.isEnabled()) {
Intent MDisc = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
MDisc.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,0);
startActivityForResult(MDisc, REQUEST_ENABLE_DSC);
}
}
#Override
public void onRestart(){
super.onRestart();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
}
break;
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(this, "BLUETOOTH NEEDS TO BE ENABLED AND DISCOVERABLE", Toast.LENGTH_SHORT).show();
finish();
}
break;
case REQUEST_ENABLE_DSC:
if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(this, "BLUETOOTH NEEDS TO BE ENABLED AND DISCOVERABLE", Toast.LENGTH_SHORT).show();
//finish();
}
break;
}
}
public void finishBTsetup(){
}
}
Despite the fact that I am setting the time to '0', discoverability only runs for 2minutes. This is rather frustrating since I know the device can handle to be discoverable for an indefinite amount of time! ( I could manually access the bluetooth settings and set Bluetooth Visibility to 'Never Time Out'!)
I've looked all over for an answer without success... many posts give what (for a relative unskilled programmer such as me) look like arcane solutions that are either too vague(*), confusing(**) or downright wrong. A simple straightforward answer solving this issue (if it exists of course!) would be greatly appreciated!
(*)
Make Bluetooth on Android 2.1 discoverable indefinitely
(**)
Extend Android Bluetooth Discoverability
Android Application Bluetooth visibility duration (answer section)
MANIFEST:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.downtoone"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="14" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
EDIT:
To give people a little context, one of the goals of this application is to try and be DISCOVERABLE to all nearby Bluetooth devices so that it can directly talk to them. Since most smartphones are discoverable for short amounts of time (2min usually*) and only so when the user directly enables discoverability (= visibility), apps that scan for devices and automatically exchange data are impossible to implement. (* The user can usually set the visibility to 'No Time Out', but that requires the user to set that option directly under Bluetooth Settings of their smartphone, which is not a very elegant solution...)
I come to the same conclusion on three devices I have.
ANDROID v 4.3 and higher : EXTRA_DISCOVERABLE_DURATION 0 works no limit
ANDROIND v 4.1 : EXTRA_DISCOVERABLE_DURATION 0 is max 1 hour. Have to change manually to no limit in parameters.
above api level 14 EXTRA_DISCOVERABLE_DURATION 0 works with infinite limit but below this it works for max 1 hour.
This code works for me
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
startActivityForResult(intent, Utils.REQUEST_DEVICE_DISCOVERABLE);
According to Android documentation, the maximum time for being discoverable is capped at 300seconds. You cannot make the BT discoverable forever.
Please see:
http://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#ACTION_REQUEST_DISCOVERABLE
In order to get the 300second maximum period, you need to change one line of code as:
MDisc.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300)
Im not sure if this would suit your application or if theres some other reason why you don't want to do this but why not just discover for the default time then restart discovery when it times out? this way it will technically be an unlimited discovery, which will only trigger a VERY slight pause in between, I used this method in my application using a broadcast receiver.
I put startDiscovery() in the onStart() method to trigger discovery on activity start, then listen to ACTION_DISCOVERY_FINISHED in your broadcast receiver's onReceive() method, here place another call to startDiscovery().
this will loop the discovery forever, if you want to stop when you find a device then call cancelDiscovery() in you receiver's ACTION_FOUND listener, you can also place some checking here if you need to find a particular device - again in my case i was checking for a particular device's mac address so the discovery would continue until this was found.
not sure if this is any use but if you need more detail let me know.
I've arrived to the conclusion that it can't be done, unless the user goes to Bluetooth > Settings > Visibility timeout and sets the timeout accordingly.
Peace.
Works to me.
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
enableBtIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
startActivityForResult(enableBtIntent, Utils.REQUEST_DEVICE_DISCOVERABLE);
Disable manually your Bluetooth and then run the code. It will works, yes.