已按 Markdown 规范重排、润色并美化了全文。以下是整理好的版本(代码保持原样未改动,原文中的截图位置已用占位符标出,方便你后续补图):


Unity Android 之 获取/设置/监听蓝牙(Bluetooth)状态方法整理

本文整理 Unity Android 开发中,如何通过 Android 原生代码获取手机蓝牙状态、设置蓝牙开关,并监听蓝牙状态变化,最终封装成 AAR 供 Unity 调用的完整方法。
项目内容
主题Unity 调用 Android 蓝牙状态接口
主要内容获取状态、设置开关、监听变化、AAR 封装
适用场景Unity Android 项目需要控制/监听蓝牙状态
环境Android Studio + Unity
难度入门

目录


一、简单介绍

本文是 Unity Android 开发中常用技术的整理笔记,方便自己日后查阅,也希望能帮助到大家。

本节主要介绍:在 Unity 开发中,如何从 Android 端获取手机蓝牙(Bluetooth)的状态、设置蓝牙开关,并监听蓝牙状态变化,同时将这些方法封装后供 Unity 调用。

💡 提示:实现方法并不唯一,欢迎交流指正。

二、实现原理

整体思路如下:

  1. 获取蓝牙适配器:调用 BluetoothAdapter.getDefaultAdapter() 获取系统蓝牙适配器对象。
  2. 获取蓝牙状态:通过 bluetoothAdapter.isEnabled() 判断蓝牙当前是否开启。
  3. 设置蓝牙开关:

    • bluetoothAdapter.enable() —— 开启蓝牙;
    • bluetoothAdapter.disable() —— 关闭蓝牙。
  4. 监听状态变化:注册广播,监听 BluetoothAdapter.ACTION_STATE_CHANGED 动作。
  5. 封装供 Unity 调用:将以上功能打包成 AAR,由 Unity 侧调用封装好的接口。

三、注意事项

3.1 添加蓝牙权限

在 AndroidManifest.xml 中声明以下权限:

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

3.2 补充提示

⚠️ 注意:从 Android 12(API 31) 开始,蓝牙相关权限升级为运行时权限 BLUETOOTH_CONNECT、BLUETOOTH_SCAN,如果目标设备系统较新,需额外适配。

四、效果预览

📷 截图占位:此处插入最终运行效果截图。

五、实现步骤

Android 端

  1. 新建 Android Library 模块
    在 Android Studio 中新建一个 Android Library 模块,其余设置保持默认即可。

    📷 截图占位:新建 Library 模块
  2. 新建脚本
    在模块中新建两个类:

    • BluetoothStateUtil —— 封装各项功能;
    • BluetoothStateInterface —— 蓝牙状态变化回调接口。
    📷 截图占位:新建脚本
  3. 编译打包 AAR
    脚本编辑完成后,执行 Build → Make Module 'xxxx',打包生成 AAR。

    📷 截图占位:打包 AAR
  4. 查看 AAR 产物
    打包成功后,在 build/outputs/aar 目录下即可找到对应的 AAR 文件。

    📷 截图占位:AAR 文件路径

Unity 端

  1. 导入 AAR
    将 Android 端打包好的 AAR 导入 Unity 工程。

    📷 截图占位:导入 AAR
  2. 搭建 UI
    在场景中布局 UI,使用 Toggle 控件显示并设置蓝牙状态。

    📷 截图占位:UI 布局
  3. 新建脚本
    在 Unity 工程中新建脚本,编写对应功能逻辑。

    📷 截图占位:新建脚本
  4. 挂载脚本并赋值
    将 TestBluetoothStateWrapper 挂载到场景对象上,并完成对应引用赋值。

    📷 截图占位:挂载脚本
  5. 运行测试
    运行场景确认无误后,即可打包到真机进行测试。
  6. 真机效果
    真机上的测试效果如上图所示。

    📷 截图占位:真机测试效果

六、关键代码

Android 端

1. BluetoothStateUtil

package com.example.bluetoothstatewrapper;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

public class BluetoothStateUtil {

    private static final String TAG = "Main_BluetoothStateUtil";

    private BluetoothAdapter bluetoothAdapter;
    private BluetoothStateBroadcastReceive mReceive;
    private Context mContext;
    private BluetoothStateInterface mBluetoothStateInterface;

    /**
     * 初始化
     */
    public void Init(BluetoothStateInterface bluetoothStateInterface) {

        // 获得蓝牙适配器对象
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mContext = getActivity();
        mBluetoothStateInterface = bluetoothStateInterface;
    }

    /**
     * 获取蓝牙状态
     */
    public boolean getBlueToothState() {
        // 获取蓝牙状态
        return bluetoothAdapter.isEnabled();
    }

    /**
     * 开启蓝牙
     */
    public boolean openBlueTooth() {
        if (getBlueToothState()) return true;
        // 打开蓝牙
        return bluetoothAdapter.enable();
    }

    /**
     * 关闭蓝牙
     */
    public boolean colseBlueTooth() {
        if (!getBlueToothState()) return true;
        // 关闭蓝牙
        return bluetoothAdapter.disable();
    }

    // 调用系统的请求打开蓝牙
    public void gotoSystem(Context context) {
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        context.startActivity(intent);
    }

    /**
     * 注册监听蓝牙变化
     */
    public void registerBluetoothReceiver() {
        if (mReceive == null) {
            mReceive = new BluetoothStateBroadcastReceive();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        intentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_OFF");
        intentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_ON");
        mContext.registerReceiver(mReceive, intentFilter);
    }

    /**
     * 取消监听蓝牙变化
     */
    public void unregisterBluetoothReceiver() {
        if (mReceive != null) {
            mContext.unregisterReceiver(mReceive);
            mReceive = null;
        }
    }

    /**
     * 蓝牙状态变化监听
     */
    class BluetoothStateBroadcastReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            switch (action) {
                case BluetoothDevice.ACTION_ACL_CONNECTED:
                    Log.i(TAG, "onReceive: " + "蓝牙设备:" + device.getName() + "已连接");
                    break;
                case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                    Log.i(TAG, "onReceive: " + "蓝牙设备:" + device.getName() + "已断开");
                    break;
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                    switch (blueState) {
                        case BluetoothAdapter.STATE_OFF:
                            Log.i(TAG, "onReceive: " + "蓝牙已关闭:");
                            mBluetoothStateInterface.onBluetoothStateOFF();
                            break;
                        case BluetoothAdapter.STATE_ON:
                            Log.i(TAG, "onReceive: " + "蓝牙已开启:");
                            mBluetoothStateInterface.onBluetoothStateON();
                            break;
                    }
                    break;
            }
        }
    }

    // 设置一个 Activity 参数
    private Activity _unityActivity;

    // 通过反射获取 Unity 的 Activity 的上下文
    Activity getActivity() {

        if (null == _unityActivity) {

            try {

                Class<?> classtype = Class.forName("com.unity3d.player.UnityPlayer");

                Activity activity = (Activity) classtype.getDeclaredField("currentActivity").get(classtype);

                _unityActivity = activity;

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        return _unityActivity;
    }
}

2. BluetoothStateInterface

package com.example.bluetoothstatewrapper;

public interface BluetoothStateInterface {

    void onBluetoothStateON();
    void onBluetoothStateOFF();
}

3. AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bluetoothstatewrapper" >

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

Unity 端

1. BluetoothStateWrapper

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace AndroidWrapper {

    /// <summary>
    /// 蓝牙状态封装
    /// 使用说明
    /// 1、首先初始化,绑定监听事件
    /// 2、可获取蓝牙状态,设置蓝牙状态
    /// 3、获得监听结果
    /// </summary>
    public class BluetoothStateWrapper : MonoSingleton<BluetoothStateWrapper>
    {

        /// <summary>
        /// 初始化
        /// </summary>
        public void Init(Action OnBluetoothStateONListener, Action OnBluetoothStateOFFListener)
        {

#if UNITY_EDITOR
#else

            MAndroidJavaObject.Call("Init", new BluetoothStateInterface(OnBluetoothStateONListener, OnBluetoothStateOFFListener));
            registerBluetoothReceiver();
#endif

        }

        /// <summary>
        /// 获得蓝牙状态
        /// </summary>
        /// <returns></returns>
        public bool getBlueToothState()
        {
            return MAndroidJavaObject.Call<bool>("getBlueToothState");
        }

        /// <summary>
        /// 开启蓝牙
        /// </summary>
        /// <returns></returns>
        public bool openBlueTooth()
        {
            return MAndroidJavaObject.Call<bool>("openBlueTooth");
        }

        /// <summary>
        /// 关闭蓝牙
        /// </summary>
        /// <returns></returns>
        public bool colseBlueTooth()
        {
            return MAndroidJavaObject.Call<bool>("colseBlueTooth");
        }

#region 私有方法

        /// <summary>
        /// 注册蓝牙状态监听
        /// </summary>
        void registerBluetoothReceiver()
        {
            MAndroidJavaObject.Call("registerBluetoothReceiver");
        }

        /// <summary>
        /// 取消注册蓝牙状态监听
        /// </summary>
        void unregisterBluetoothReceiver()
        {
            MAndroidJavaObject.Call("unregisterBluetoothReceiver");
        }

        protected override void OnDestroy()
        {
            unregisterBluetoothReceiver();
            base.OnDestroy();
        }

#endregion

#region 私有变量

        AndroidJavaObject _mAndroidJavaObject;

        public AndroidJavaObject MAndroidJavaObject
        {
            get
            {
                if (_mAndroidJavaObject == null)
                {
                    _mAndroidJavaObject = new AndroidJavaObject("com.example.bluetoothstatewrapper.BluetoothStateUtil");
                }

                return _mAndroidJavaObject;
            }
        }

#endregion
    }
}

2. BluetoothStateInterface

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace AndroidWrapper
{
    /// <summary>
    /// 蓝牙状态监听接口
    /// </summary>
    public class BluetoothStateInterface : AndroidJavaProxy
    {
        /// <summary>
        /// 蓝牙变化委托事件
        /// </summary>
        Action _mBluetoothStateON;
        Action _mBluetoothStateOFF;

        public BluetoothStateInterface(Action mBluetoothStateON, Action mBluetoothStateOFF)
            : base("com.example.bluetoothstatewrapper.BluetoothStateInterface")
        {
            _mBluetoothStateON = mBluetoothStateON;
            _mBluetoothStateOFF = mBluetoothStateOFF;
        }

        /// <summary>
        /// 蓝牙打开事件监听
        /// </summary>
        public void onBluetoothStateON()
        {
            if (_mBluetoothStateON != null)
            {
                _mBluetoothStateON();
            }

            Debug.Log(GetType() + "/onBluetoothStateON()/ 蓝牙开启事件");
        }

        /// <summary>
        /// 蓝牙关闭事件监听
        /// </summary>
        public void onBluetoothStateOFF()
        {
            if (_mBluetoothStateOFF != null)
            {
                _mBluetoothStateOFF();
            }

            Debug.Log(GetType() + "/onBluetoothStateOFF()/ 蓝牙关闭事件");
        }
    }
}

3. TestBluetoothStateWrapper

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using AndroidWrapper;
using UnityEngine.UI;

public class TestBluetoothStateWrapper : MonoBehaviour
{
    public Toggle BTState_Toggle;

    // Start is called before the first frame update
    void Start()
    {
        BluetoothStateWrapper.Instance.Init(SetOnToggle, SetOffToggle);
        InitToggle();
    }

    /// <summary>
    /// 初始化
    /// </summary>
    void InitToggle() {

#if UNITY_EDITOR

        // 获取当前状态
        SetIsOnToggle(Random.Range(0, 2) == 0 ? false : true);
        // 设置监听事件
        BTState_Toggle.onValueChanged.AddListener((isOn) => {

        });
#else

        // 获取当前状态
        SetIsOnToggle(BluetoothStateWrapper.Instance.getBlueToothState());
        // 设置监听事件
        BTState_Toggle.onValueChanged.AddListener((isOn) => {
            if (isOn == true)
            {
                BluetoothStateWrapper.Instance.openBlueTooth();
            }
            else {
                BluetoothStateWrapper.Instance.colseBlueTooth();
            }
        });

#endif
    }

    void SetOnToggle() {
        SetIsOnToggle(true);
    }

    void SetOffToggle()
    {
        SetIsOnToggle(false);
    }

    void SetIsOnToggle(bool isOn) {
        BTState_Toggle.isOn = isOn;
    }
}

4. MonoSingleton

using UnityEngine;

public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T instance = null;

    private static readonly object locker = new object();

    private static bool bAppQuitting;

    public static T Instance
    {
        get
        {
            if (bAppQuitting)
            {
                instance = null;
                return instance;
            }

            lock (locker)
            {
                if (instance == null)
                {
                    instance = FindObjectOfType<T>();
                    if (FindObjectsOfType<T>().Length > 1)
                    {
                        Debug.LogError("不应该存在多个单例!");
                        return instance;
                    }

                    if (instance == null)
                    {
                        var singleton = new GameObject();
                        instance = singleton.AddComponent<T>();
                        singleton.name = "(singleton)" + typeof(T);
                        singleton.hideFlags = HideFlags.None;
                        DontDestroyOnLoad(singleton);
                    }
                    else
                        DontDestroyOnLoad(instance.gameObject);
                }
                instance.hideFlags = HideFlags.None;
                return instance;
            }
        }
    }

    protected virtual void Awake()
    {
        bAppQuitting = false;
    }

    protected virtual void OnDestroy()
    {
        bAppQuitting = true;
    }
}

整理说明:以上内容在保留原文信息与代码的前提下,对标题层级、目录、代码块高亮、列表、提示框等做了 Markdown 规范化排版;原文中的截图请按 📷 截图占位 位置补入即可。

最后修改:2026 年 12 月 05 日
如果觉得我的文章对你有用,请随意赞赏