Android蓝牙(一)

一、蓝牙简介

1.权限

<!-- 控制蓝牙的权限 -->
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!-- 获取蓝牙信息权限,使用蓝牙必须的权限 -->
<uses-permission android:name="android.permission.BLUETOOTH" />

二、常用类

1.BluetoothAdapter

对象获取方法

private BluetoothAdapter myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

常见属性

属性介绍
STATE_OFF值为10, 蓝牙模块处于关闭状态
STATE_TURNING_ON值为11, 蓝牙模块正在打开ing
STATE_ON值为12, 蓝牙模块处于开启状态
STATE_TURNING_OFF值为13, 蓝牙模块正在关闭ing
SCAN_MODE_NONE值为20, 查询扫描和页面扫描都失效, 该状态下蓝牙模块既不能扫描其它设备, 也不可见
SCAN_MODE_CONNECTABLE值为21, 查询扫描失效, 页面扫描有效, 该状态下蓝牙模块可以扫描其它设备, 从可见性来说只对已配对的蓝牙设备可见, 只有配对的设备才能主动连接本设备
SCAN_MODE_CONNECTABLE_DISCOVERABLE值为23, 查询扫描和页面扫描都有效
ACTION_DISCOVERY_FINISHED蓝牙适配器完成搜索发出的广播, 值为”android.bluetooth.adapter.action.DISCOVERY_FINISHED”, 需要BLUETOOTH权限
ACTION_LOCAL_NAME_CHANGED本地的蓝牙适配器改变了自己的名称,值为”android.bluetooth.adapter.action.SCAN_MODE_CHANGED”, 该Intent对象包含了EXTRA_SCAN_MODE和EXTRA_PREVIOUS_SCAN_MODE, 两个附加域分别是新的和旧的扫描模式, 这里可以根据前后扫描模式的不同做出不同的操作, 需要BLUETOOTH权限
ACTION_STATE_CHANGED蓝牙模块被打开或者关闭, 值为”android.bluetooth.adapter.action.STATE_CHANGED”, 该广播的Intent中包含EXTRA_STATE和EXTRA_PREVIOUS_STATE两个附加域, 需要BLUETOOTH权限

常用方法

方法介绍
cancelDiscovery()取消搜索
disable()关闭蓝牙(不通知用户)
enable()打开蓝牙(不通知用户)
getAddress()获取地址
getDefaultAdapter()获取BluetoothAdapter
getName()获取蓝牙名字
getRemoteDevice(String address)根据蓝牙地址获取远程蓝牙设备
getState()获取本地蓝牙适配器当前状态(感觉可能调试的时候更需要)
isDiscovering()判断当前是否正在查找设备,是返回true
isEnabled()判断蓝牙是否打开,已打开返回true
startDiscovery()开始搜索,其实是开启一个广播,返回信息在广播中

2.BluetoothDevice

很多和BluetoothAdapter差不多

方法介绍
getState()蓝牙状态,只有在 BluetoothAdapter.STATE_ON 状态下才可以监听
getAddress()获取地址
getName()获取名字

3.BluetoothServerSocket

4.BluetoothSocket

三、打开、关闭、搜索蓝牙

1.先上效果图

效果图

2.代码

/**
 * 我这里用了xUtils3框架和我自己写的ToastUtil,在我的优化Toast中有说
 */
@ContentView(R.layout.activity_bluetooth)
public class BluetoothActivity extends BaseActivity {

    /**
     * ACTION_FOUND 搜索状态
     * BOND_BONDED 绑定状态
     * ACTION_DISCOVERY_FINISHED 搜索完成
     */

    private Context context;
    private BluetoothAdapter myBluetoothAdapter;
    /**
     * 自定义广播类
     */
    private BaseBroadcastReceiver myBluetoothReceiver = new BaseBroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BluetoothDevice.ACTION_FOUND)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // 不搜索已经绑定的蓝牙设备
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    LogUtil.i("搜索到的设备:" + device.getName() + ":" + device.getAddress());
                }
            } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                ToastUtil.showToast(context, "搜索完成");
            }
        }
    };

    @ViewInject(R.id.show)
    private TextView show;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        context = BluetoothActivity.this;
        myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        getBoundedBluetooth();

        // 注册用以接收到已搜索到的蓝牙设备的receiver
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);//
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(myBluetoothReceiver, filter);
    }
    /**
     * 获取已经绑定的蓝牙设备
     */
    public void getBoundedBluetooth() {
        Set<BluetoothDevice> devices = myBluetoothAdapter.getBondedDevices();
        if (devices.size() > 0) {
            for (BluetoothDevice bluetoothDevice : devices) {
                show.append("已经绑定了的:" + bluetoothDevice.getName() + ":" + bluetoothDevice.getAddress() + "\n\n");
            }
        }
    }

    /**
     * 打开蓝牙
     * @param view
     */
    @Event(R.id.open)
    private void openBluetooth(View view) {

        if (myBluetoothAdapter == null) {
            ToastUtil.showToast(context, "本机没有找到蓝牙硬件或驱动!");
        }
        if (!myBluetoothAdapter.isEnabled()) {
            Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(mIntent, 1);
        }
    }

    /**
     * 用户打开蓝牙时,选择的返回处理
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                ToastUtil.showToast(context, "蓝牙已经开启");
            } else if (resultCode == RESULT_CANCELED) {
                ToastUtil.showToast(context, "不允许蓝牙开启");
            }
        }
    }

    /**
     * 关闭蓝牙
     * @param view
     */
    @Event(R.id.close)
    private void closeBluetooth(View view) {
        if (myBluetoothAdapter.isEnabled()) {
            myBluetoothAdapter.disable();
            ToastUtil.showToast(context, "蓝牙已经关闭");
        }
    }

    /**
     * 扫描附近的蓝牙设备
     * @param view
     */
    @Event(R.id.find)
    private void findBluetooth(View view) {
        ToastUtil.showToast(context, "启动扫描!");
        // 如果正在搜索,就先取消搜索
        if (myBluetoothAdapter.isDiscovering()) {
            myBluetoothAdapter.cancelDiscovery();
        }
        // 开始搜索蓝牙设备,搜索到的蓝牙设备通过广播返回,这是一个广播发送者
        myBluetoothAdapter.startDiscovery();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除注册
        unregisterReceiver(myBluetoothReceiver);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值