Android 蓝牙

概念:

蓝牙( Bluetooth® ):是一种无线技术标准,可实现固定设备、移动设备和楼宇个人域网之间的短距离数据交换(使用2.4—2.485GHz的ISM波段的UHF无线电波)。蓝牙技术最初由电信巨头爱立信公司于1994年创制,当时是作为RS232数据线的替代方案。蓝牙可连接多个设备,克服了数据同步的难题。

如今蓝牙由蓝牙技术联盟(Bluetooth Special Interest Group,简称SIG)管理。蓝牙技术联盟在全球拥有超过25,000家成员公司,它们分布在电信、计算机、网络、和消费电子等多重领域。IEEE将蓝牙技术列为IEEE 802.15.1,但如今已不再维持该标准。蓝牙技术联盟负责监督蓝牙规范的开发,管理认证项目,并维护商标权益。制造商的设备必须符合蓝牙技术联盟的标准才能以“蓝牙设备”的名义进入市场。蓝牙技术拥有一套专利网络,可发放给符合标准的设备。


操作:

权限


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

一、获取蓝牙

//获取默认的 bluetootAdapter
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

BluetoothAdapter的属性打开时才能够读取和更改(设备启用状态),如果该设备关闭,那么这些方法将返回空。

二、判断设备开起,更改设备信息

//当蓝牙开启时
            if(bluetooth.isEnabled()){
                //蓝牙地址
                String address = bluetooth.getAddress();
                //蓝牙名称
                String name = bluetooth.getName();
                Toast.makeText(this,"Address:"+address+" name:"+name,Toast.LENGTH_LONG).show();
                //蓝牙设备开启时并且添加 BLUETOOTH_ADMIN 权限 可以对蓝牙进行名称设定
//                bluetooth.setName("挖掘机哪家强");
                //扫描蓝牙设备
                blueToothScan();
            }else{
                //当蓝牙未开启时
                Toast.makeText(this,"蓝牙未开启",Toast.LENGTH_LONG).show();
                //弹出提示用户打开蓝牙
                startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), START_BLUETOOTH);
            }

 打开返回

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    //打开蓝牙返回
    if(requestCode== START_BLUETOOTH &&resultCode==RESULT_OK){
       Toast.makeText(this,"打开蓝牙",Toast.LENGTH_SHORT).show();
    }  
}

三、注册打开蓝牙广播

//注册蓝牙打开广播
registerReceiver(bluetoothState,new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));

/**
     * 创建蓝牙监听广播
     */

    BroadcastReceiver bluetoothState = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
            int previousState = intent.getIntExtra( BluetoothAdapter.EXTRA_PREVIOUS_STATE, -1);

//            int state = bluetooth.getState();
            switch (state){
                case BluetoothAdapter.STATE_TURNING_ON:
                    //打开中
                    break;
                case BluetoothAdapter.STATE_ON:
                    //已打开
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    //关闭中
                    break;
                case BluetoothAdapter.STATE_OFF:
                    //已关闭
                    break;
            }
        }
    };

四、注册可被扫描广播

//注册可被扫描广播
registerReceiver(bluetoothScan,new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED));

//扫描状态广播
BroadcastReceiver bluetoothScan=new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        int prevMode = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_SCAN_MODE, -1);
        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;
        }
    }
};

/**
 * 开始扫描
 */
private void blueToothScan(){
    int scanMode = bluetooth.getScanMode();
    if(scanMode==BluetoothAdapter.SCAN_MODE_NONE){
        //设置设备可以被发现
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        //设置可发现时间
        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,60);
        startActivityForResult(intent, START_DISCOVERABLE);
    }else{
        //是否正在扫描,正在扫描取消扫描
        mDeviceAdapter.clearDevice();
        if(!bluetooth.isDiscovering()){
           bluetooth.startDiscovery();
        }else{
            //停止扫描
            bluetooth.cancelDiscovery();
            //开始扫描
            bluetooth.startDiscovery();
        }
    }
}

五、注册开始扫描和结束扫描广播

//注册扫描开始
registerReceiver(discoveryMonitor,new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
//注册扫描结束
registerReceiver(discoveryMonitor,new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));

BroadcastReceiver discoveryMonitor = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(BluetoothAdapter.ACTION_DISCOVERY_STARTED==intent.getAction()){
            Log.i(TAG,"开始扫描 start");
        }else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED==intent.getAction()){
            Log.i(TAG,"结束扫描 finish");
        }
    }
};

六、注册设备扫描结果

//注册设备扫描结果
registerReceiver(discoveryResult,new IntentFilter(BluetoothDevice.ACTION_FOUND));

//扫描结果
BroadcastReceiver discoveryResult = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        //名称
        String remoteName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
        //设备
        BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        mDeviceAdapter.addDevice(remoteDevice);
    }
}

七、退出时unRegisterReceiver

@Override
protected void onDestroy() {
    unregisterReceiver(bluetoothState);
    unregisterReceiver(bluetoothScan);
    unregisterReceiver(discoveryMonitor);
    unregisterReceiver(discoveryResult);
    super.onDestroy();
}


你可能感兴趣的:(android,蓝牙)