Bluetooth app turn on

How to enable/disable bluetooth programmatically in android

For this to work, you must have the following permissions:

it really works for me also. simple method to disconnect the bluetooth in android devices. thanks a lot buddy.

if you add BLUETOOTH_ADMIN permission it’s work but if not you need to use startActivityForResult(enableBtIntent, 0); to enable your bluetooth

Thanks for your useful answer +1 . just I want to add for who doesn’t know how to enable it: mBluetoothAdapter.enable()

Those manifest permissions do not work for me in 2022. The correct one is android.permission.BLUETOOTH_CONNECT . Otherwise it will give permission but will not disable.

Here is a bit more robust way of doing this, also handling the return values of enable()\disable() methods:

public static boolean setBluetooth(boolean enable) < BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); boolean isEnabled = bluetoothAdapter.isEnabled(); if (enable && !isEnabled) < return bluetoothAdapter.enable(); >else if(!enable && isEnabled) < return bluetoothAdapter.disable(); >// No need to change bluetooth state return true; > 

And add the following permissions into your manifest file:

But remember these important points:

This is an asynchronous call: it will return immediately, and clients should listen for ACTION_STATE_CHANGED to be notified of subsequent adapter state changes. If this call returns true, then the adapter state will immediately transition from STATE_OFF to STATE_TURNING_ON, and some time later transition to either STATE_OFF or STATE_ON. If this call returns false then there was an immediate problem that will prevent the adapter from being turned on — such as Airplane mode, or the adapter is already turned on.

Ok, so how to implement bluetooth listener?:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() < @Override public void onReceive(Context context, Intent intent) < final String action = intent.getAction(); if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) < final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); switch (state) < case BluetoothAdapter.STATE_OFF: // Bluetooth has been turned off; break; case BluetoothAdapter.STATE_TURNING_OFF: // Bluetooth is turning off; break; case BluetoothAdapter.STATE_ON: // Bluetooth is on break; case BluetoothAdapter.STATE_TURNING_ON: // Bluetooth is turning on break; >> > >; 

And how to register/unregister the receiver? (In your Activity class)

@Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); // . // Register for broadcasts on BluetoothAdapter state change IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); registerReceiver(mReceiver, filter); >@Override public void onStop() < super.onStop(); // . // Unregister broadcast listeners unregisterReceiver(mReceiver); >

if you add BLUETOOTH_ADMIN permission it’s work but if not you need to use startActivityForResult(enableBtIntent, 0); to enable your bluetooth

hey, the docs say that Bluetooth should never be enabled without direct user consent. If you want to turn on Bluetooth in order to create a wireless connection, you should use the ACTION_REQUEST_ENABLE Intent, which will raise a dialog that requests user permission to turn on Bluetooth. The enable() method is provided only for applications that include a user interface for changing system settings, such as a «power manager» app. What does it mean? For ex. I made a little app from your code and it worked. But if I want to upload to Play Store, it won’t work?

@Hilal it will work. But users need to give consent before installation. They will see a dialog like this: pewinternet.org/2015/11/10/…

Android BluetoothAdapter docs say it has been available since API Level 5. API Level 5 is Android 2.0.

Читайте также:  Avic mrz099 подключение блютуз

You can try using a backport of the Bluetooth API (have not tried it personally): http://code.google.com/p/backport-android-bluetooth/

To Enable the Bluetooth you could use either of the following functions:

The difference is that the first function makes the app ask the user a permission to turn on the Bluetooth or to deny. The second function makes the app turn on the Bluetooth directly.

To Disable the Bluetooth use the following function:

NOTE/ The first function needs only the following permission to be defined in the AndroidManifest.xml file:

While, the second and third functions need the following permissions:

The solution of prijin worked perfectly for me. It is just fair to mention that two additional permissions are needed:

When these are added, enabling and disabling works flawless with the default bluetooth adapter.

I used the below code to disable BT when my app launches and works fine. Not sure if this the correct way to implement this as google recommends not using «bluetooth.disable();» without explicit user action to turn off Bluetooth.

 BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); bluetooth.disable(); 

I only used the below permission.

One may have problems with this method if the app is dependent on Bluetooth being off because there is a race condition since bluetooth.disable() is asynchronous.

You must perform the standard permission request for BLUETOOTH_CONNECT as you would when requesting permission for storage or other «prompted» items.

val bluetoothAdapter = (getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter if (bluetoothAdapter.isEnabled) bluetoothAdapter.disable() 

For Android 12 and above, BLUETOOTH and BLUETOOTH_ADMIN permissions are not necessary to retrieve the current state or toggle it, unless targeting lower APIs.

This doesn’t seem to work, are you sure it’s supported on Android 12+? I tested on a Pixel 5 running Android 13

@behelit Android 13 removed the ability to enable and disable the adapter. No alternative, just stripped it from the developers.

BluetoothAdapter is deprecated from Android OS13. Is there any alternate to enable the bluetooth programatically on OS13?

@tklanilkumar Google specifically removed that option. It appears you are stuck with using the intents now. Google is creating the illusion of safety through poorly designed and excessive popups. The more it has to look like malware, the less likely you are to bother at all or something like that.

I have made a class to handle almost all this in Kotlin using Coroutines

 class ActivityResultHandler( private val registry: ActivityResultRegistry ) < private val handlers = mutableListOf>() fun unregisterHandlers() < handlers.forEach < it.unregister() >> suspend fun requestLocationPermission(): Boolean < return suspendCoroutine < continuation ->val launcher = registry.register( LOCATION_PERMISSION_REQUEST, // lifecycleOwner, ActivityResultContracts.RequestPermission() ) < continuation.resumeWith(Result.success(it)) >handlers.add(launcher) launcher.launch(Manifest.permission.ACCESS_FINE_LOCATION) > > suspend fun requestBluetoothActivation(): Boolean < return suspendCoroutine < continuation ->val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE) val launcher = registry.register( BLUETOOTH_ON_REQUEST, // lifecycleOwner, ActivityResultContracts.StartActivityForResult() ) < result ->continuation.resume( result.resultCode == Activity.RESULT_OK ) > handlers.add(launcher) launcher.launch(enableBtIntent) > > fun checkLocationPermission(context: Context): Boolean < return ContextCompat.checkSelfPermission( context, Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED >private suspend fun requestLocationActivation( intentSenderRequest: IntentSenderRequest, ): Boolean < return suspendCoroutine < continuation ->val launcher = registry.register( LOCATION_ACTIVATION_REQUEST, // lifecycleOwner, ActivityResultContracts.StartIntentSenderForResult() ) < continuation.resume(it.resultCode == Activity.RESULT_OK) >handlers.add(launcher) launcher.launch(intentSenderRequest) > > suspend fun enableLocation(context: Context): Boolean = suspendCoroutine < continuation ->val locationSettingsRequest = LocationSettingsRequest.Builder() // .setNeedBle(true) .addLocationRequest( LocationRequest.create().apply < priority = LocationRequest.PRIORITY_HIGH_ACCURACY >) .build() val client: SettingsClient = LocationServices.getSettingsClient(context) val task: Task = client.checkLocationSettings(locationSettingsRequest) task.addOnSuccessListener < continuation.resume(true) >task.addOnFailureListener < exception ->if (exception is ResolvableApiException && exception.statusCode == LocationSettingsStatusCodes.RESOLUTION_REQUIRED ) < val intentSenderRequest = IntentSenderRequest.Builder(exception.resolution).build() CoroutineScope(continuation.context).launch < val result = requestLocationActivation(intentSenderRequest) continuation.resume(result) >> else < continuation.resume(false) >> > companion object < private const val LOCATION_PERMISSION_REQUEST = "LOCATION_REQUEST" private const val BLUETOOTH_ON_REQUEST = "LOCATION_REQUEST" private const val LOCATION_ACTIVATION_REQUEST = "LOCATION_REQUEST" >> 
// make sure you extend AppCompatActivity class MainActivity : AppCompatActivity() < private val permissionRequests = ActivityResultHandler(activityResultRegistry) override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // use viewmodels and fragments instead of GlobalScope GlobalScope.launch < // turn on bluetooth permissionRequests.requestBluetoothActivation() // to be able to scan for devices you also need location permission // also show pop up to let users know why you need location // https://support.google.com/googleplay/android-developer/answer/9799150?hl=en permissionRequests.requestLocationPermission() // also you need navigation to be enabled permissionRequests.enableLocation(this@MainActivity) >> override fun onDestroy() < super.onDestroy() permissionRequests.unregisterHandlers() >> 

coroutines dependency in gradle

Читайте также:  Vw polo 2014 bluetooth

also add this permissions to manifest

Источник

How to turn on bluetooth on button click

In my application, I need to turn on bluetooth of my device on a button click. How can I achieve that? An example will be really helpful. Also, what permissions I require to include in my mainfest.xml for the same?

3 Answers 3

In the manifest file for permissions:

Source code to enable Bluetooth

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) < // Device does not support Bluetooth >if (!mBluetoothAdapter.isEnabled())

If enabling Bluetooth succeeds, your Activity will receive the RESULT_OK result code in the onActivityResult() callback. If Bluetooth was not enabled due to an error (or the user responded «No») then the result code will be RESULT_CANCELED .

Don’t forget there is another way to turn on bluetooth without using the Intent request. Just call mBluetoothAdapter.enable(); this will turn it on without user popup permission dialog. (only use this way if no user input wanted)

@JPM yes, but 1) this requires BLUETOOTH_ADMIN permission; 2) it’s strongly discouraged in the Android SDK documentation to ever use enable() unless you implement your own UI for user consent or if you’re implementing a system settings manager app or similar.

Turn on Bluetooth in Android it’s not difficult.But you must pay attention to some details.There are 3 kinds of methods to turn on Bluetooth in Android.

In order to get the default bluetooth adapter, ie use BluetoothAdapter.getDefaultAdapter() ; You need this permission:

In order to force to open Bluetooth, ie use BluetoothAdapter.enable() ; You need this permission:

/** * Bluetooth Manager * * @author ifeegoo www.ifeegoo.com * */ public class BluetoothManager < /** * Whether current Android device support Bluetooth. * * @return true:Support Bluetooth false:not support Bluetooth */ public static boolean isBluetoothSupported() < return BluetoothAdapter.getDefaultAdapter() != null ? true : false; >/** * Whether current Android device Bluetooth is enabled. * * @return true:Bluetooth is enabled false:Bluetooth not enabled */ public static boolean isBluetoothEnabled() < BluetoothAdapter bluetoothAdapter = BluetoothAdapter .getDefaultAdapter(); if (bluetoothAdapter != null) < return bluetoothAdapter.isEnabled(); >return false; > /** * Force to turn on Bluetooth on Android device. * * @return true:force to turn on Bluetooth success * false:force to turn on Bluetooth failure */ public static boolean turnOnBluetooth() < BluetoothAdapter bluetoothAdapter = BluetoothAdapter .getDefaultAdapter(); if (bluetoothAdapter != null) < return bluetoothAdapter.enable(); >return false; > > 

The method above to turn on Bluetooth will not tell the user whether you turn on Bluetooth success or not.When you call the method enable(), you will not turn on Bluetooth 100%.Because of the reason of some security apps refuse you to do this and so on.You need to pay attention to the return value of the method enable().

Читайте также:  Kali linux подключить bluetooth наушники

The official api of the method enable() tells us that :

Bluetooth should never be enabled without direct user consent. If you want to turn on Bluetooth in order to create a wireless connection, you should use the ACTION_REQUEST_ENABLE Intent, which will raise a dialog that requests user permission to turn on Bluetooth. The enable() method is provided only for applications that include a user interface for changing system settings, such as a “power manager” app.

So it’s not suitable for you to turn on Bluetooth by the method enable() unless you make the user know what you will do.

2.Use System Alert to remind users that you will turn on Bluetooth by startActivityForResult.

this.startActivityForResult(requestBluetoothOn, REQUEST_CODE_BLUETOOTH_ON) need this permission: public class MainActivity extends Activity < /** * Custom integer value code for request to turn on Bluetooth,it's equal *requestCode in onActivityResult. */ private static final int REQUEST_CODE_BLUETOOTH_ON = 1313; /** * Bluetooth device discovery time,second。 */ private static final int BLUETOOTH_DISCOVERABLE_DURATION = 250; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_main); if ((BluetoothManager.isBluetoothSupported()) && (!BluetoothManager.isBluetoothEnabled())) < this.turnOnBluetooth(); >> /** * Use system alert to remind user that the app will turn on Bluetooth */ private void turnOnBluetooth() < // request to turn on Bluetooth Intent requestBluetoothOn = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE); // Set the Bluetooth discoverable. requestBluetoothOn .setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); // Set the Bluetooth discoverable time. requestBluetoothOn.putExtra( BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, BLUETOOTH_DISCOVERABLE_DURATION); // request to turn on Bluetooth this.startActivityForResult(requestBluetoothOn, REQUEST_CODE_BLUETOOTH_ON); >@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) < if (requestCode == REQUEST_CODE_BLUETOOTH_ON) < switch (resultCode) < // When the user press OK button. case Activity.RESULT_OK: < // TODO >break; // When the user press cancel button or back button. case Activity.RESULT_CANCELED: < // TODO >break; default: break; > > > > 

This is a better way for you to turn on Bluetooth on Android.

3.Guide users to the system Bluetooth settings to turn on Bluetooth by themselves.

// Guide users to system Bluetooth settings to turn on Bluetooth by himselves. this.startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)); 

In my app.Considering the code logical and also the user experience, I use the follow steps to turn on Bluetooth:

1.use enable() to turn on Bluetooth.But I will tell the users that I will turn on Bluetooth, if they allow me to do this, I will call enable() to turn on Bluetooth.This is better than call the system alert, because we can control the content to remind user. You must pay attention that it’s not 100% to turn on Bluetooth by enable() , some security apps or other reasons refuse you to do this.But we can estimate that whether we turn on Bluetooth success or not by the return value of the method enable().

2.If the method enable() return false,then we use startActivityForResult to remind users that we will turn on Bluetooth.

3.If the step 2 will not work by some reasons, you can guide the users to go to the system Bluetooth settings to turn on Bluetooth by themselves.

Add more:since Android 6.0 we need to deal with the permission of Bluetooth.

Источник

Оцените статью
Adblock
detector