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

发布于 2024-11-18 04:22:02 字数 118 浏览 2 评论 0原文

在我的应用程序中,我需要通过单击按钮打开设备的蓝牙。我怎样才能做到这一点?一个例子会很有帮助。另外,我需要什么权限才能在我的 mainfest.xml 中包含相同的内容?

In my application, I need to turn on bluetooth of my device on a button click. How can I achieve that? An example will be really helpful. Also, what permissions I require to include in my mainfest.xml for the same?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

绿萝 2024-11-25 04:22:02

有关蓝牙的 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

Following are code excerpts from android documentation on Bluetooth

In the manifest file for permissions:

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

Source code to enable Bluetooth

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

If enabling Bluetooth succeeds, your Activity will receive the RESULT_OK result code in the onActivityResult() callback. If Bluetooth was not enabled due to an error (or the user responded "No") then the result code will be RESULT_CANCELED.

全部不再 2024-11-25 04:22:02

在Android中打开蓝牙并不困难。但是您必须注意一些细节。在Android中打开蓝牙有3种方法。

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()时,你不会100%打开蓝牙。因为一些安全应用拒绝你这样做的原因等等。你需要注意enable()方法的返回值。

方法enable()的官方api告诉我们:

未经用户直接同意,绝对不应该启用蓝牙。如果要打开蓝牙以创建无线连接,则应使用 ACTION_REQUEST_ENABLE 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()方法打开蓝牙并不是100%的,有些安全应用或者其他原因会拒绝你这样做。但是我们可以通过该方法的返回值来判断是否打开蓝牙成功。使能够()。

2.如果enable()方法返回false,那么我们使用startActivityForResult来提醒用户我们将打开蓝牙。

3.如果由于某些原因步骤2无法进行,您可以引导用户进入系统蓝牙设置自行打开蓝牙。

补充:从Android 6.0开始我们需要处理蓝牙的权限。

Turn on Bluetooth in Android it's not difficult.But you must pay attention to some details.There are 3 kinds of methods to turn on Bluetooth in Android.

1.Force to open Bluetooth.

In order to get the default bluetooth adapter, ie use BluetoothAdapter.getDefaultAdapter(); You need this permission:

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

In order to force to open Bluetooth, ie use BluetoothAdapter.enable(); You need this permission:

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

Here is a code sample

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

The method above to turn on Bluetooth will not tell the user whether you turn on Bluetooth success or not.When you call the method enable(), you will not turn on Bluetooth 100%.Because of the reason of some security apps refuse you to do this and so on.You need to pay attention to the return value of the method enable().

The official api of the method enable() tells us 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.

So it's not suitable for you to turn on Bluetooth by the method enable() unless you make the user know what you will do.

2.Use System Alert to remind users that you will turn on Bluetooth by 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;
            }
        }
    }
}

This is a better way for you to turn on Bluetooth on Android.

3.Guide users to the system Bluetooth settings to turn on Bluetooth by themselves.

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

In my app.Considering the code logical and also the user experience, I use the follow steps to turn on Bluetooth:

1.use enable() to turn on Bluetooth.But I will tell the users that I will turn on Bluetooth, if they allow me to do this, I will call enable() to turn on Bluetooth.This is better than call the system alert, because we can control the content to remind user.
You must pay attention that it's not 100% to turn on Bluetooth by enable() , some security apps or other reasons refuse you to do this.But we can estimate that whether we turn on Bluetooth success or not by the return value of the method enable().

2.If the method enable() return false,then we use startActivityForResult to remind users that we will turn on Bluetooth.

3.If the step 2 will not work by some reasons, you can guide the users to go to the system Bluetooth settings to turn on Bluetooth by themselves.

Add more:since Android 6.0 we need to deal with the permission of Bluetooth.

何时共饮酒 2024-11-25 04:22:02

此解决方案将为您Android 蓝牙提供帮助。但有关 Android 蓝牙使用情况以及 manifest.xml 的详细信息,您需要查看此 安卓蓝牙

对于您需要的许可。

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

This solution will help you Android Bluetooth. But for details about the Bluetooth usage with Android along with manifest.xml you need to see this Android Bluetooth.

For permission you need.

<manifest ... >
  <uses-permission android:name="android.permission.BLUETOOTH" />
  ...
</manifest>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文