android bluetooth development - basics

Basic knowledge of android bluetooth development

1. I recently studied Bluetooth development to share with you Xiaobai's learning experience
. First, understand the sharp tools in Bluetooth development.

private BluetoothAdapter mBluetoothAdapter;

It controls the realization of most functions of the Bluetooth module
(1) Whether the device has a Bluetooth module

    //实例化蓝牙适配器
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    //判断蓝牙功能呢是否存在
    if (mBluetoothAdapter == null) {
        showToast("无蓝牙模块");
        return;
    }

(2) Obtain Bluetooth information and operating status

    //获取名字和mac地址/当前蓝牙状态(打开,关闭,正在连接.....)
    String name = mBluetoothAdapter.getName();
    String mac = mBluetoothAdapter.getAddress();
    int state = mBluetoothAdapter.getState();
    //判断状态
    switch (state) {
        case BluetoothAdapter.STATE_ON:  //蓝牙已经打开
            break;
        case BluetoothAdapter.STATE_TURNING_ON://蓝牙正在打开
            break;
        case BluetoothAdapter.STATE_TURNING_OFF://蓝牙正在关闭
            break;
        case BluetoothAdapter.STATE_OFF://蓝牙已经关闭
            break;
    }

(3) Two ways to turn on Bluetooth

            public static final int REQUEST_OPEN = 0x01;//打开一个蓝牙

               //强制打开蓝牙
                /*boolean isOpen = mBluetoothAdapter.enable();
                showToast("" + isOpen);*/
                //调用系统API中action打开(start Activity for result)
                Intent open = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(open, REQUEST_OPEN);

(4) Download the demo if you want to see the source code (free drop)
http://download.csdn.net/download/gywuhengy/9813413

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325479188&siteId=291194637