Bluetooth turning off android

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?

Читайте также:  Тойота рав 4 подключение телефона через bluetooth

@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.

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

Читайте также:  Меняется mac адрес bluetooth

also add this permissions to manifest

Источник

Toggling Bluetooth on and off?

Is there a simple tutorial or dose anyone have code to toggle Bluetooth on and off using a Toggle-button in eclipse building for android? If anyone can help that will be greatly appreciated. -Thanks in advance.

6 Answers 6

in your manifest file, and variables like:

private final integer REQUEST_ENABLE_BT = 1; 
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); boolean hasBluetooth = (mBluetoothAdapter == null); 

so that in your OnCreate you can do something like:

final ToggleButton togglebutton = (ToggleButton) findViewById(R.id.togglebutton); togglebutton.setOnClickListener(new OnClickListener() < public void onClick(View v) < // Perform action on clicks if (togglebutton.isChecked()) < if (hasBluetooth && !mBluetoothAdapter.isEnabled()) < // prompt the user to turn BlueTooth on Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); >> else < if (hasBluetooth && mBluetoothAdapter.isEnabled()) < // you should really prompt the user for permission to turn // the BlueTooth off as well, e.g., with a Dialog boolean isDisabling = mBluetoothAdapter.disable(); if (!isDisabling) < // an immediate error occurred - perhaps the bluetooth is already off? >> > > >); 

where the user response to the «turn bluetooth on» prompt is caught in

protected void onActivityResult (int requestCode, int resultCode, Intent data) < if ((requestCode == REQUEST_ENABLE_BT) && (resultCode == RESULT_OK)) < boolean isEnabling = mBluetoothAdapter.enable(); if (!isEnabling) < // an immediate error occurred - perhaps the bluetooth is already on? >else if (mBluetoothAdapter.getState() == BluetoothAdapter.STATE_TURNING_ON) < // the system, in the background, is trying to turn the Bluetooth on // while your activity carries on going without waiting for it to finish; // of course, you could listen for it to finish yourself - eg, using a // ProgressDialog that checked mBluetoothAdapter.getState() every x // milliseconds and reported when it became STATE_ON (or STATE_OFF, if the // system failed to start the Bluetooth.) >> > 

Источник

How to Turn Off Your Phone’s Bluetooth Permanently

Michael Archambault is a technology writer and digital media specialist. His work has appeared in Mobile Nations, Amazon’s Digital Photography Review, PetaPixel, and other outlets.

Michael Heine is a CompTIA-certified writer, editor, and Network Engineer with 25+ years’ experience working in the television, defense, ISP, telecommunications, and education industries.

Читайте также:  Внутриканальные блютуз наушники sony

What To Know

  • To temporarily turn off on iOS: Go to Control Center and tap the Bluetooth icon.
  • To permanently turn off on iOS: Go to Settings >Bluetooth, and toggle Bluetooth off.
  • On Android: Go to Settings >Connected Devices >Connection Preferences >Bluetooth. Toggle Bluetooth off.

This article explains how to turn off Bluetooth on your Android device or an iPhone. This information applies to iOS 14 through iOS 12 and Android 10 and later.

How to Turn Off Bluetooth on iPhone Temporarily

If you only want to disconnect a pair of headphones or another Bluetooth accessory from your iPhone, you can do so via Control Center.

To access Control Center on the iPhone, slide your finger downward from the upper-right corner (in iOS 12 and later) or upward from the bottom of the screen (in earlier versions of the iOS).

The Control Center displays some quick settings for screen brightness, Bluetooth, Wi-Fi, and a Do Not Disturb function. Tap the Bluetooth icon to disconnect all non-Apple devices.

iPhone Control Center with Bluetooth icon highlighted

The resulting screen shows the Bluetooth icon in a white background and displays the message «Disconnecting Bluetooth Devices Until Tomorrow,» so this option is not permanent.

While this toggle switch may achieve your end goal of disconnecting a pair of headphones, it leaves the Bluetooth radio on for some additional functions and services, such as the Apple Watch, Apple Pencil, and Mac Handoff feature.

How to Turn Off Bluetooth Permanently in iOS

If you want to shut off Bluetooth entirely, you do so in the iPhone Settings app. While most users will be satisfied with shutting off partial Bluetooth functionality via the Control Center, those who don’t use any Bluetooth devices or the Mac Handoff functionality may want to turn the radio off entirely in exchange for a little more battery life.

In the Settings app, select Bluetooth and then tap the toggle switch next to Bluetooth to shut it off entirely. The resulting screen warns that AirPlay, AirDrop, Find My, Location Services, and Exposure Notifications use Bluetooth.

iPhone Settings showing the Bluetooth settings

How to Turn Off Bluetooth on Android

Due to the variety of different Android smartphone manufacturers, turning off Bluetooth varies between devices. However, when you choose to toggle off Bluetooth on an Android device, it’s shut off permanently until you decide to reengage it.

One option for deactivating Bluetooth on an Android device is via the Status Bar. Swipe down from the top of the screen to display the Status Bar and swipe down again to locate and tap Bluetooth to switch it on or off.

Status Bar open to show Bluetooth icon

Another option for turning off your Android device’s Bluetooth is via the Settings app. Launch it and go to Connected Devices > Connection Preferences > Bluetooth. Tap the toggle switch to deactivate your device’s Bluetooth functionality.

In addition to helping extend battery life, shutting off Bluetooth can prevent possible hacking schemes. One common Android Bluetooth hack is known as BlueBorne; it can allow users to gain unauthorized access to your device. Turning off Bluetooth when it isn’t in use improves overall security.

Источник

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