如何在按钮点击时打开蓝牙

7

在我的应用程序中,我需要在按钮点击时打开我的设备的蓝牙。我该如何实现?一个例子将非常有帮助。另外,我需要在我的mainfest.xml中包含哪些权限?


1
https://dev59.com/0HI-5IYBdhLWcg3wMFS0 - Ozair Kafray
3个回答

8
以下是来自Android蓝牙文档的代码摘录:
在权限清单文件中添加以下内容:
<manifest ... >
  <uses-permission android:name="android.permission.BLUETOOTH" />
  ...
</manifest>

启用蓝牙的源代码

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
    // Device does not support Bluetooth
}

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

如果启用蓝牙成功,您的Activity将在onActivityResult()回调中接收到RESULT_OK结果代码。如果由于错误(或用户响应“否”)而未启用蓝牙,则结果代码将为RESULT_CANCELED

6
不要忘记还有一种方法可以打开蓝牙,而不需要使用Intent请求。只需调用mBluetoothAdapter.enable();这将在没有用户弹出权限对话框的情况下打开蓝牙。(仅在不需要用户输入时使用此方法) - JPM
2
@JPM 是的,但需要以下两点:1)这需要“BLUETOOTH_ADMIN”权限; 2) 在Android SDK文档中,强烈不建议使用enable()除非您实现了自己的用户同意UI或者您正在实现系统设置管理器应用程序或类似应用。 - JHH

5

在安卓系统中打开蓝牙并不难,但你需要注意一些细节。有三种方法可以打开安卓系统的蓝牙。

1.强制打开蓝牙。

为了获取默认的蓝牙适配器,即使用BluetoothAdapter.getDefaultAdapter()方法;你需要获得以下权限:

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

为了强制打开蓝牙,即使用BluetoothAdapter.enable(); 您需要这个权限:
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

这里有一个代码示例:
/**
 * 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;
    }
}

上述打开蓝牙的方法并不能告知用户是否已成功打开蓝牙。当调用enable()方法时,你可能并不会成功打开蓝牙。这是因为一些安全应用程序会拒绝此类操作等原因。你需要注意该方法的返回值。
enable()方法的官方API告诉我们:
未经用户直接同意,不应启用蓝牙。如果您想打开蓝牙以创建无线连接,则应使用ACTION_REQUEST_ENABLE Intent,该Intent将引发一个对话框,请求用户权限以打开蓝牙。enable()方法仅提供给包含更改系统设置的用户界面(例如“电源管理器”应用程序)的应用程序使用。
因此,除非你让用户知道你要做什么,否则通过enable()方法打开蓝牙不太合适。
2.使用系统提醒来提示用户,通过startActivityForResult打开蓝牙。
this.startActivityForResult(requestBluetoothOn, REQUEST_CODE_BLUETOOTH_ON) 
need this permission:
<uses-permission android:name="android.permission.BLUETOOTH" />


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

这是一种更好的方法,让您在Android上打开蓝牙。

3.引导用户进入系统蓝牙设置中自行打开蓝牙。

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

在我的应用程序中,为了考虑代码逻辑和用户体验,我使用以下步骤打开蓝牙:
1. 使用 enable() 方法来打开蓝牙。但是,在告知用户之后再调用 enable() 方法打开蓝牙会更好,因为我们可以控制提醒用户的内容。需要注意的是,并非所有情况都能通过 enable() 方法成功打开蓝牙,例如某些安全应用或其他原因可能拒绝。但我们可以通过 enable() 方法的返回值来判断是否开启成功。
2. 如果 enable() 方法返回 false,则使用 startActivityForResult 提醒用户我们将要打开蓝牙。
3. 如果第二步由于某些原因无法工作,可以引导用户前往系统蓝牙设置页面自行打开蓝牙。
此外,从 Android 6.0 开始,我们需要处理蓝牙权限的问题。

0

这个解决方案将帮助你Android蓝牙。但是,如果你想了解有关在Android上使用蓝牙以及manifest.xml的详细信息,你需要查看Android蓝牙

你需要权限。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接