Android Studio第三十三期 - 蓝牙开发初识~

时间:2024-05-21 17:37:09

    遇见到坑爹的队友只有接受现实并且解决问题~

    Android Studio第三十三期 - 蓝牙开发初识~

    首先介绍一下网上几乎所有的能搜到的方法:

    1.首先,要操作蓝牙,先要在AndroidManifest.xml里加入权限

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

    2.在android.bluetooth包下就这些能用的东西:

Android Studio第三十三期 - 蓝牙开发初识~

    3.我们一般用的是BluetoothAdapter基本就可以实现需求了:

      cancelDiscovery() :取消发现,也就是说当我们正在搜索设备的时候调用这个方法将不再继续搜索

      disable():关闭蓝牙

      enable():打开蓝牙,这个方法打开蓝牙不会弹出提示,更多的时候我们需要问下用户是否打开,一下这两行代码同样是打开蓝牙,不过会提示用户:

1
2
3
4
5
6
7
8
9
//打开蓝牙
if (!mBluetoothAdapter.isEnabled()) {
    Intent intent1 = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intent1, ENABLE_BLUE);
    //不做提示,强行打开
    // mAdapter.enable();
else {
    close_blue();
}

    

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == ENABLE_BLUE) {
        if (resultCode == RESULT_OK) {
            Toast.makeText(this"蓝牙开启成功", Toast.LENGTH_SHORT).show();
            open_blue();
        else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(this"蓝牙开始失败", Toast.LENGTH_SHORT).show();
            close_blue();
        }
    }
}

      getAddress():获取本地蓝牙地址

      getDefaultAdapter():获取默认BluetoothAdapter,实际上,也只有这一种方法获取BluetoothAdapter

      getName():获取本地蓝牙名称

      getRemoteDevice(String address):根据蓝牙地址获取远程蓝牙设备

      getState():获取本地蓝牙适配器当前状态(感觉可能调试的时候更需要)

      isDiscovering():判断当前是否正在查找设备,是返回true

      isEnabled():判断蓝牙是否打开,已打开返回true,否则,返回false

     listenUsingRfcommWithServiceRecord(String name,UUID uuid):根据名称,UUID创建并返回BluetoothServerSocket,这是创建BluetoothSocket服务器端的第一步

      startDiscovery():开始搜索,这是搜索的第一步


    4.使设备能够被搜索:

    首先判断初始状态:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//本机设备被扫描初始状态bufen
if (mBluetoothAdapter.getScanMode() == 23) {
    //开启状态设置bufen
            //开启操作
        //弹窗
//                    Intent intent = new Intent(
//                            BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//                    //设置蓝牙可见性的时间,方法本身规定最多可见300秒
//                    intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, BLUE_TIME);
//                    startActivityForResult(intent, SEARCH_BLUE);
        //不弹窗
        SettingblueUtils.setDiscoverableTimeout(120);
        shezhi_blue_research(true);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                closeDiscoverableTimeout();
                shezhi_blue_research(false);
            }
        }, 1201000);
else if (mBluetoothAdapter.getScanMode() == 21) {
    //关闭状态设置bufen
    closeDiscoverableTimeout();
}

    然后设置代码部分:

    开启:

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void setDiscoverableTimeout(int timeout) {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    try {
        Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout"int.class);
        setDiscoverableTimeout.setAccessible(true);
        Method setScanMode = BluetoothAdapter.class.getMethod("setScanMode"int.classint.class);
        setScanMode.setAccessible(true);
        setDiscoverableTimeout.invoke(adapter, timeout);
        setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE, timeout);
    catch (Exception e) {
        e.printStackTrace();
    }
}

    关闭:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void closeDiscoverableTimeout() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    try {
        Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout"int.class);
        setDiscoverableTimeout.setAccessible(true);
        Method setScanMode = BluetoothAdapter.class.getMethod("setScanMode"int.classint.class);
        setScanMode.setAccessible(true);
 
        setDiscoverableTimeout.invoke(adapter, 1);
        setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE, 1);
    catch (Exception e) {
        e.printStackTrace();
    }
}

    

    5.抓取蓝牙列表List的方法:

1
2
3
4
5
6
// 获取所有已经绑定的蓝牙设备
Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
List<BluetoothDevice> mList1 = new ArrayList<>();
if (devices.size() > 0) {
    mList1 = new ArrayList<>(devices);
}

   

    6.注册搜索蓝牙receiver:

1
2
3
4
5
6
IntentFilter mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
mFilter.addAction(BluetoothDevice.ACTION_FOUND);
mFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
mFilter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
mFilter.addAction(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED);
registerReceiver(mReceiver, mFilter);

    

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
 
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        String action = intent.getAction();
        // 获得已经搜索到的蓝牙设备
        if (action.equals(BluetoothDevice.ACTION_FOUND)) {
            BluetoothDevice device11 = intent
                    .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // 搜索到的不是已经绑定的蓝牙设备
            if (!is_shebei_open) {
                receiver1(device11);
            else {
                receiver11(device11);
            }
            /**当绑定的状态改变时*/
        else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
            BluetoothDevice device22 = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            receiver2(device22, MainActivity_BlueTooth.this);
        else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
            receiver3();
        else if (action.equals(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED)) {
            int state = intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, BluetoothA2dp.STATE_DISCONNECTED);
            receiver4(state);
        else if (action.equals(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED)) {
            int state = intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, BluetoothA2dp.STATE_NOT_PLAYING);
            receiver5(state);
        }
    }
};

 

    最后说一下,多连接目前还没有解决,个人试了很多方法,大家如果有方法告诉我,谢谢~









本文转自 吴雨声 51CTO博客,原文链接:http://blog.51cto.com/liangxiao/1905941,如需转载请自行联系原作者