对于低功耗的蓝牙设备,在Android4.3(API18)有支持*/

权限:

<span style="font-size:12px;"> <!-- 任意蓝牙的交互如:请求连接、接受连接、传输数据都需要此权限-->
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <!-- 让蓝牙设备可见、操作蓝牙设置需要此权限,当需要此权限时必须加上上面的权限-->
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/></span></span>

下面是对蓝牙的一些基本操作:

<span style="font-size:12px;">public class BlueToothOp {
    private BluetoothAdapter adapter;

    public BlueToothOp() {
        adapter = BluetoothAdapter.getDefaultAdapter();
    }

    //检测蓝牙是否存在
    public boolean isExist() {
        if (adapter == null)
            return false;
        return true;
    }

    //检测蓝牙是否可用
    public boolean isEnable() {
        return adapter.isEnabled();
    }

    //蓝牙是否可见
    public boolean isCover() {
        return adapter.isDiscovering();
    }

    //打开蓝牙
    public void open(Activity activity, int requestCode) {
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        activity.startActivityForResult(intent, requestCode);
    }

    //设置蓝牙设备可见
    public void openDiscover(Activity activity, int requestCode) {
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        activity.startActivityForResult(intent, requestCode);
    }

    //关闭蓝牙
    public void close() {
        adapter.disable();
    }
}</span>

回调方法:

<span style="font-size:12px;">    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0 && resultCode == RESULT_OK){
            showToast("打开蓝牙成功");
        }
        if(requestCode == 1 && resultCode == RESULT_OK){
            showToast("打开蓝牙失败");
        }
        //当你选择取消时候resultCode返回RESULT_CANCELED
    }</span>

当然你的应用也可以监听

ACTION_STATE_CHANGED,需要注册广播:

<span style="font-size:12px;">       IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(receiver,intentFilter);

    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int action = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,-1);
            switch (action){
                case BluetoothAdapter.STATE_TURNING_ON:
                    System.out.println("正在打开");
                    break;
                case BluetoothAdapter.STATE_ON:
                    System.out.println("打开完毕");
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    System.out.println("正在关闭");
                    break;
                case BluetoothAdapter.STATE_OFF:
                    System.out.println("关闭完毕");
                    break;
                case BluetoothAdapter.STATE_CONNECTED://连接
                    System.out.println("连接完毕");
                    break;
                case BluetoothAdapter.STATE_CONNECTING://正在连接
                    System.out.println("正在连接");
                    break;
            }
        }
    };</span>


使用BluetoothAdapter你可以发现远程设备通过设备的discovery,也可以得到设备与远程设备绑定的集合。设备的发现更像是一个搜索周围设备的过程,然后一个在该区域的设备将会去响应该请求,前提是该设备可用并且是可见的;响应的信息包括设备的名字、类、MAC地址,使用这些信息便可以进行连接。

连接和匹配是有区别的,匹配:两个设备都知道彼此的存在,可用于身份的验证并能够建立一个加密的连接;连接:目前设备共享RFCOOM通道可以共享数据。(当两个设备之前匹配过,他们将自动进行匹配)

得到匹配的设备:


Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices 
if (pairedDevices.size() > 0) {
    // Loop through paired devices 
    for (BluetoothDevice device : pairedDevices) {
        // Add the name and address to an array adapter to show in a ListView 
        mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
    } 
}

得到发现的设备:

通过调用startDiscovery()便可以进行发现设备。这个方法返回一个Boolean的值来表明是否发现是否成功开始,为了得到发现的设备,我们的应用必须要注册一个广播,行为:ACTION_FOUND,每一次的发现我们可以通过Intent来得到BluetoothDevice对象

// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // Add the name and address to an array adapter to show in a ListView
            mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
    }
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

tips:发现设备是一个很复杂的过程会耗费很多的资源,一旦你发现了一个设备并进行连接,应确保你的设备停止去发现(通过你调用cancelDiscovery来实现)

设置可被发现的:

代码如下:

Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);

tips:默认这个设备成为可见的是120秒,这个最大值为3600秒,0秒代表这个设备总是可见的,当不再0~3600之间则自动设置120秒


具体的广播接受者:

IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);//开始发现
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//发现完成
        intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);//扫描模式发生改变
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//远程设备被发现
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//绑定状态发生改变
        registerReceiver(receiver, intentFilter);
BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
                //开始发现设备
            } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                //发现完成
            } else if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {
                //扫描模式发生改变
                int scanMode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, -1);
                switch (scanMode) {
                    case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE://发现但保持连接
                        //发现但保持连接
                        break;
                    case BluetoothAdapter.SCAN_MODE_CONNECTABLE://没发现但保持连接
                        //没发现但保持连接
                        break;
                    case BluetoothAdapter.SCAN_MODE_NONE://没有发现也没有保持连接
                        //没有发现也没有保持连接
                        break;
                }
            } else if (action.equals(BluetoothDevice.ACTION_FOUND)) {
                //发现设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                //发现设备   名字:" + device.getName() + "   MAC地址:" + device.getAddress()
            } else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
                //绑定状态发生改变
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if(device == null){
                    //"该设备不存在不能进行绑定"
                    return;
                }
                int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,-1);
                switch (bondState){
                    case BluetoothDevice.BOND_BONDING:
                        //正在绑定
                        break;
                    case BluetoothDevice.BOND_BONDED:
                        //绑定完成
                        break;
                    case BluetoothDevice.BOND_NONE:
                        //绑定未成功
                        break;
                }
            }
        }
    };