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

时间:2010-09-27 18:07:03

标签: android bluetooth

我想通过该程序启用/禁用蓝牙。我有以下代码。

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

但是这个代码在SDK 1.5中不起作用。我怎样才能使它发挥作用?

9 个答案:

答案 0 :(得分:151)

这段代码对我有用..

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

要使其正常工作,您必须具有以下权限:

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

答案 1 :(得分:83)

这是一种更健壮的方法,也处理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;
}

并将以下权限添加到清单文件中:

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

但请记住以下几点:

  

这是一个异步调用:它将立即返回,并返回客户端   应该听取ACTION_STATE_CHANGED以获得后续通知   适配器状态更改。如果此调用返回true,则适配器   state将立即从STATE_OFF转换为STATE_TURNING_ON,   一段时间后转换到STATE_OFF或STATE_ON。如果   这个调用返回false然后会出现一个直接的问题   防止适配器打开 - 例如飞行模式,或   适配器已经打开。

<强>更新

好的,那么如何实现蓝牙监听器?:

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 has been on
                break;
            case BluetoothAdapter.STATE_TURNING_ON:
                // Bluetooth is turning on
                break;
            }
        }
    }
};

如何注册/取消注册接收器? (在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);
}

答案 2 :(得分:29)

Android BluetoothAdapter文档称自API级别5以来一直可用。API Level 5是Android 2.0。

您可以尝试使用蓝牙API的后端端口(尚未亲自尝试过):http://code.google.com/p/backport-android-bluetooth/

答案 3 :(得分:22)

要启用蓝牙,您可以使用以下任一功能:

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

第二个功能是:

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

不同之处在于第一个功能使应用程序要求用户启用蓝牙或拒绝。第二个功能使应用程序直接打开蓝牙。

要禁用蓝牙,请使用以下功能:

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

注意/第一个功能只需要在AndroidManifest.xml文件中定义以下权限:

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

同时,第二个和第三个功能需要以下权限:

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

答案 4 :(得分:5)

prijin的解决方案对我来说非常合适。公平地说,需要两个额外的权限:

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

添加这些功能后,默认蓝牙适配器可以启用和禁用启用和禁用。

答案 5 :(得分:4)

当我的应用启动并且工作正常时,我使用以下代码禁用BT。不确定这是否是正确的方法来实现这一点谷歌建议不要使用“bluetooth.disable();”没有明确的用户操作来关闭蓝牙。

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

我只使用了以下许可。

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

答案 6 :(得分:2)

将以下权限添加到清单文件中:

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

启用蓝牙使用此

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

禁用蓝牙使用此

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

答案 7 :(得分:0)

试试这个:

//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();
        }
    }

在清单

中添加这些权限
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

答案 8 :(得分:0)

我创建了一个类来使用协程在 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"
    }
}

像这样使用它:

// 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()
    }
}

gradle 中的协程依赖

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

还要将此权限添加到清单中

    <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" />