以编程方式在 Android 上启用蓝牙 [英] Programmatically enabling bluetooth on Android

查看:21
本文介绍了以编程方式在 Android 上启用蓝牙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定在 Android 上以编程方式启用蓝牙的首选方式.我发现以下任一技术都有效(至少在 Android 4.0.4 上...):

I'm trying to determine the preferred way for programmatically enabling bluetooth on Android. I've found that either of the following techniques works (at least on Android 4.0.4...):

public class MyActivity extends Activity {
    public static final int MY_BLUETOOTH_ENABLE_REQUEST_ID = 6;
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, MY_BLUETOOTH_ENABLE_REQUEST_ID);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MY_BLUETOOTH_ENABLE_REQUEST_ID) {
            if (resultCode == RESULT_OK) {
                // Request granted - bluetooth is turning on...
            }
            if (resultCode == RESULT_CANCELED) {
                // Request denied by user, or an error was encountered while 
                // attempting to enable bluetooth
            }
        }
    }

或...

BluetoothAdapter.getDefaultAdapter().enable();

前者在启用前询问用户许可,而后者只是默默启用蓝牙(但需要android.permission.BLUETOOTH_ADMIN"许可).一种或另一种旧/过时和/或一种技术仅在某些设备上可用吗?或者这只是我个人喜好的问题?

The former asks the user for permission prior to enabling while the latter just silently enables bluetooth (but requires the "android.permission.BLUETOOTH_ADMIN" permission). Is one or the other old/obsolete and/or is one technique only available on some devices? or is it just a matter of personal preference as to which I use?

推荐答案

Android 中明确提到 文档

It is clearly mentioned in Android Doc

未经用户直接同意,不得启用蓝牙.如果您想打开蓝牙以创建无线连接,您应该使用 ACTION_REQUEST_ENABLE 意图,这将引发一个对话框,请求用户允许打开蓝牙.enable() 方法仅适用于包含用于更改系统设置的用户界面的应用程序,例如电源管理器"应用程序.

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.

这两种技术都行.您必须根据您的目的和要求进行选择.希望它能回答您的问题.

Both of these techniques would work. You have to choose based on your purpose and requirement. Hope it answers your questions.

这篇关于以编程方式在 Android 上启用蓝牙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆