简体   繁体   English

如何在android中以编程方式启用/禁用蓝牙

[英]How to enable/disable bluetooth programmatically in android

I want to enable/disable bluetooth through the program.我想通过程序启用/禁用蓝牙。 I have the following code.我有以下代码。

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

But this code is not working in SDK 1.5.但此代码不适用于 SDK 1.5。 How can I make it work?我怎样才能让它工作?

this code worked for me..这段代码对我有用..

//Disable bluetooth
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (mBluetoothAdapter.isEnabled()) {
    mBluetoothAdapter.disable(); 
} 

For this to work, you must have the following permissions:为此,您必须具有以下权限:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

Here is a bit more robust way of doing this, also handling the return values of enable()\\disable() methods:这是一个更健壮的方法,还处理enable()\\disable()方法的返回值:

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:并将以下权限添加到您的清单文件中:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

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.这是一个异步调用:它将立即返回,并且客户端应该侦听 ACTION_STATE_CHANGED 以收到后续适配器状态更改的通知。 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.如果此调用返回 true,则适配器状态将立即从 STATE_OFF 转换为 STATE_TURNING_ON,一段时间后转换为 STATE_OFF 或 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.如果此调用返回 false,则表示存在将阻止打开适配器的即时问题 - 例如飞行模式,或适配器已打开。

UPDATE:更新:

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) (在你的Activity课上)

@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);
}

Android BluetoothAdapter docs say it has been available since API Level 5. API Level 5 is Android 2.0. Android BluetoothAdapter文档说它从 API Level 5 开始就可用了。 API Level 5是 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/您可以尝试使用蓝牙 API 的 backport(没有亲自尝试过): http : //code.google.com/p/backport-android-bluetooth/

To Enable the Bluetooth you could use either of the following functions:要启用蓝牙,您可以使用以下任一功能:

 public void enableBT(View view){
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (!mBluetoothAdapter.isEnabled()){
        Intent intentBtEnabled = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
        // The REQUEST_ENABLE_BT constant passed to startActivityForResult() is a locally defined integer (which must be greater than 0), that the system passes back to you in your onActivityResult() 
        // implementation as the requestCode parameter. 
        int REQUEST_ENABLE_BT = 1;
        startActivityForResult(intentBtEnabled, REQUEST_ENABLE_BT);
        }
  }

The second function is:第二个功能是:

public void enableBT(View view){
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (!mBluetoothAdapter.isEnabled()){
        mBluetoothAdapter.enable();
    }
}

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.第二个功能让app直接开启蓝牙。

To Disable the Bluetooth use the following function:要禁用蓝牙,请使用以下功能:

public void disableBT(View view){
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter.isEnabled()){
        mBluetoothAdapter.disable();
    }
}

NOTE/ The first function needs only the following permission to be defined in the AndroidManifest.xml file:注意/ 第一个函数只需要在 AndroidManifest.xml 文件中定义以下权限:

<uses-permission android:name="android.permission.BLUETOOTH"/>

While, the second and third functions need the following permissions:同时,第二个和第三个功能需要以下权限:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

The solution of prijin worked perfectly for me. prijin 的解决方案对我来说非常有效。 It is just fair to mention that two additional permissions are needed:公平地说,需要两个额外的权限:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

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.当我的应用程序启动并正常工作时,我使用以下代码禁用 BT。 Not sure if this the correct way to implement this as google recommends not using "bluetooth.disable();"不确定这是否是实现这一点的正确方法,因为谷歌建议不要使用“bluetooth.disable();” without explicit user action to turn off Bluetooth.没有明确的用户操作来关闭蓝牙。

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

I only used the below permission.我只使用了以下权限。

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

Add the following permissions into your manifest file:将以下权限添加到您的清单文件中:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

Enable bluetooth use this启用蓝牙使用这个

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (!mBluetoothAdapter.isEnabled()) {
    mBluetoothAdapter.enable(); 
}else{Toast.makeText(getApplicationContext(), "Bluetooth Al-Ready Enable", Toast.LENGTH_LONG).show();}

Disable bluetooth use this禁用蓝牙使用这个

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (mBluetoothAdapter.isEnabled()) {
    mBluetoothAdapter.disable(); 
}

Updated for Android 12:针对 Android 12 更新:

AndroidManifest.xml - AndroidManifest.xml -

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>

You must perform the standard permission request for BLUETOOTH_CONNECT as you would when requesting permission for storage or other "prompted" items.您必须像请求存储或其他“提示”项目的权限一样执行BLUETOOTH_CONNECT的标准权限请求。

Usage (Kotlin) -用法(科特林) -

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

try this:试试这个:

//this method to check bluetooth is enable or not: true if enable, false is not enable
public static boolean isBluetoothEnabled()
    {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            // Bluetooth is not enable :)
            return false;
        }
        else{
            return true;
        }

    }

//method to enable bluetooth
    public static void enableBluetooth(){
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }
    }

//method to disable bluetooth
    public static void disableBluetooth(){
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.disable();
        }
    }

Add these permissions in manifest在清单中添加这些权限

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

I have made a class to handle almost all this in Kotlin using Coroutines我创建了一个类来使用 Coroutines 在 Kotlin 中处理几乎所有这些


class ActivityResultHandler(
    private val registry: ActivityResultRegistry
) {

    private val handlers = mutableListOf<ActivityResultLauncher<*>>()

    fun unregisterHandlers() {
        handlers.forEach {
            it.unregister()
        }
    }

    suspend fun requestLocationPermission(): Boolean {
        return suspendCoroutine<Boolean> { 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<Boolean> { 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<LocationSettingsResponse> =
                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"
    }
}

Use it like this:像这样使用它:

// 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 gradle 中的协程依赖

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.2'

also add this permissions to manifest还要将此权限添加到清单

    <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-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM