Android BLE蓝牙管理类

本文详细介绍了蓝牙扫描管理类BleScannerManager的功能和使用方法,包括蓝牙设备的扫描、监听、开启和关闭等操作,以及如何设置扫描间隔和蓝牙监听器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 蓝牙扫描管理类
 */
public class BleScannerManager {

    public static final String TAG = "BleScannerManager";
    /**
     * 默认扫描间隔
     */
    public static final long DEFAULT_SCAN_TIME = 12000;
    /**
     * 扫描间隔
     */
    private long mScanCurrentTime = DEFAULT_SCAN_TIME;

    private static BleScannerManager instance;

    private final BluetoothAdapter mBluetoothAdapter;
    private final Context mContext;
    private BleListener mBleListener;

    public static BleScannerManager getInstance(Context context) {
        if (instance == null) {
            synchronized (BleScannerManager.class) {
                if (instance == null) {
                    instance = new BleScannerManager(context.getApplicationContext());
                }
            }
        }
        return instance;
    }

    private BleScannerManager(Context context) {
        BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        this.mContext = context;
    }

    public void setBleListener(boolean start, BleListener bleListener) {
        this.mBleListener = bleListener;

        if (enableBluetooth() && start) {
            startScan();
        }
    }

    public static final boolean isGpsEnable(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否支持蓝牙设备
     *
     * @return
     */
    private boolean isBluetoothValid() {
        if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            if (mBleListener != null) {
                mBleListener.onEnableFail("设备不支持蓝牙");
            }
            Log.e(TAG, " 设备不支持蓝牙");
            return false;
        }
        if (mBluetoothAdapter == null) {
            if (mBleListener != null) {
                mBleListener.onEnableFail("获取蓝牙失败");
            }
            Log.e(TAG, " 获取蓝牙失败");
            return false;
        }
        return true;
    }

    public boolean isBleOpen() {
        if (!isBluetoothValid()) {
            return false;
        }
        return mBluetoothAdapter.isEnabled();
    }

    public boolean closeBle() {
        if (!isBluetoothValid()) {
            return false;
        }
        return mBluetoothAdapter.disable();
    }

    public boolean enableBluetooth() {
        if (!isBluetoothValid()) {
            Log.e(TAG, " isBluetoothValid enableBluetooth");
            return false;
        }
        try {
            if (!mBluetoothAdapter.isEnabled()) {
                if (mBluetoothAdapter.enable()) {
                    if (mBleListener != null) {
                        Log.e(TAG, " mBluetoothAdapter onEnableSuccess");
                        mBleListener.onEnableSuccess();
                        return true;
                    }
                } else {
                    if (mBleListener != null) {
                        mBleListener.onEnableFail("打开蓝牙失败");
                    }
                    return false;
                }
            }
            if (mBleListener != null) {
                Log.e(TAG, "mBleListener onEnableSuccess");
                mBleListener.onEnableSuccess();
            }
            return true;
        } catch (Exception e) {
            if (mBleListener != null) {
                mBleListener.onEnableFail("打开蓝牙异常");
            }
            Log.e(TAG, "打开蓝牙异常");
        }
        return false;
    }

    private Handler mScanHandler;

    public void startScan() {

        if (mScanHandler == null) {
            doScan();
        }
        if (mBleListener != null) {
            mBleListener.onStartSearch();
        }
    }

    private BluetoothAdapter.LeScanCallback mLeScanCallback;

    private void doScan() {
        if (mScanHandler == null) {
            mScanHandler = new Handler(mContext.getMainLooper());
        }
        if (mLeScanCallback == null) {
            mLeScanCallback = new LowScanCallback();
        }
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
        mBluetoothAdapter.startLeScan(mLeScanCallback);
        mScanHandler.removeMessages(0);
        mScanHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                doScan();
            }
        }, mScanCurrentTime);
    }

    public void stopScan() {
        if (mScanHandler != null) {
            mScanHandler.removeMessages(0);
            mScanHandler = null;
        }
        if (mBluetoothAdapter != null) {
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        if (mBleListener != null) {
            mBleListener.onStopSearch();
        }
        mBleListener = null;
    }

    private class LowScanCallback implements BluetoothAdapter.LeScanCallback {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            String name = device.getName();
            ThreadUtils.postUI(new Runnable() {
                @Override
                public void run() {
                    if (mBleListener != null) {
                        mBleListener.LeScanResult(device);
                    }
                }
            });

        }
    }

    interface BleListener {

        void onStartSearch();

        void LeScanResult(BluetoothDevice device);

        void onStopSearch();

        void onEnableSuccess();

        void onEnableFail(String msg);
    }
}

 

最近因为有关于BLE 4.0的项目,写了一个管理。 直接讲CBManager拉到项目里就可以使用。项目本身是一个demo。但是关于BLE的东西你还是需要自己去了解一下。发现设备的手机是Central,去发现周边的Peripheral,选中要连接的peripheral之后,获取它的service,再从service里拿它持有的characters,每一个characters会有不同的权限,一般是read,write,notify,incate之。read比较的简单,但是write涉及到不同的设备,协议不同,所以写入的数据需要你自己去具体实现。demo里只是简单的把你的string转换成十六进制的ACSII,打包成NSData发送出去。 如果你的service和character的name是unknow,你需要去项目里的ServiceAndCharacters.plist文件里添加字段,把你的设备的UUID和对应的name写进去就可以了。这个是自定义的部分。基本除了Device Infomation都是Unknown,根据你自己的需要改吧。 具体的使用看demo吧。 但是还有部分完善的就是需要加一些提示的部分,读写controller里面我也没怎么管Label和UITexxtView的布局了。。。 那个基本都是需要你自己项目自定义的东西。下方有我的github地址,我会在那里更新。 因为连接的过程中程序没有处理,还允许你点击其他的peripheral去连接,可能会出现问题。一个设备只有两个状态,被连接以后就不能去连接和发现其他设备了。 Github地址: https://github.com/leeB0Wen/BLEDemo 有问题可以私聊或者github上戳我
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值