蓝牙开发(一)基础设置

1、添加权限

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

2、判断设备是否支持

BluetoothAdapter:本机蓝牙适配器

BluetoothDevice:远程蓝牙设备

是否支持蓝牙:

BluetoothAdapter mBluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null ){
    //设备不支持蓝牙
}

3、判断当前蓝牙状态

mBluetoothAdapter.isEnabled();

4、打开蓝牙

如果当前蓝牙状态为关闭,那么打开蓝牙(最好使用友好的蓝牙打开方式)

public void turnOnBluetooth(Activity activity, int requestCode){
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    activity.startActivityForResult(intent, requestCode);
}

5、关闭蓝牙

mBluetoothAdapter.disable();

注意:该方法没有弹框提示

6、监听蓝牙状态的广播

private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
            switch (state) {
                case BluetoothAdapter.STATE_OFF:
                    UIUtils.showToast(getActivity(), "state_off");
                    break;
                case BluetoothAdapter.STATE_ON:
                    //已打开
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    //正在打开
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    //正在关闭
                    break;
                default:
                    //未知状态
                    break;
            }
        }
    };
//onCreate中注册广播
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(receiver,filter);

猜你喜欢

转载自blog.csdn.net/PanADE/article/details/82500142