类微信实现Bluetooth聊天

类微信实现Bluetooth聊天(Fragment中使用Bluetooth)

要求:
1.窗口标题栏显示“无连接”,单击右上角三点可选择“我的好友”,进入另一个配对好友界面;
2.选择好友之后,返回主界面,标题栏会显示选择的的手机;
3.两个连接的手机可进行蓝牙聊天。

类微信界面其他部分功能的部署的见之前的博客
类微信界面: https://blog.csdn.net/qq_44841678/article/details/105005148.
类微信界面+RecyclerView: https://blog.csdn.net/qq_44841678/article/details/105080025.
类微信界面读取联系人:https://blog.csdn.net/qq_44841678/article/details/105919005.

注意点:

此程序需要得到蓝牙使用权限,用在清单文件里注册的方法来配置;
准备:
在清单文件AndroidManifest.xml里,添加两行:

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

实现蓝牙通信需要这两个权限,整个项目运行,其他版块还需要的权限可见之前的代码。

实现界面展示:

      

.xml文件:

tab01.xml:
在tab01.xml(即weixinFragment对应的布局文件)里,添加1个Toolbar控件,其内包含2个水平的TextView控件;在Toolbar控件的下方添加1个ListView控件,用于显示聊天内容;最后在ListView控件的下方添加水平放置的1个EditText控件和一个Button控件。具体代码见库。

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/title_left_text"
            style="?android:attr/windowTitleStyle"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:layout_weight="1"
            android:gravity="left"
            android:ellipsize="end"
            android:singleLine="true" />
        <TextView
            android:id="@+id/title_right_text"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_weight="1"
            android:ellipsize="end"
            android:gravity="right"
            android:singleLine="true"
            android:textColor="#fff" />
    </LinearLayout>
</androidx.appcompat.widget.Toolbar>

点右上角三点之后出现的小框布局文件:res -> new ->Android Resource Directory -> Resource type换成menu ->
新建res/menu/option_menu.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/scan"
        android:icon="@android:drawable/ic_menu_myplaces"
        android:title="@string/connect" />
    <item android:id="@+id/discoverable"
        android:icon="@android:drawable/ic_menu_view"
        android:title="@string/discoverable" />
    <item android:id="@+id/back"
        android:icon="@android:drawable/ic_menu_close_clear_cancel"
        android:title="@string/back" />
</menu>

device_list.xml:(用于显示“我的好友”,即已配对的设备,和搜索好友)代码见库。
decive_name.xml和message.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:id="@+id/text1"
    android:gravity="center_vertical"
    android:textSize="22sp"
    android:text="文本数据"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
事件监听控制:

ChatService.java:
用于蓝牙会话的服务组件ChatService,有3个内部类:AcceptThread(接受新连接)、ConnectThread(发出连接)和ConnectedThread (已连接)。
部分代码:

    // 创建监听线程,准备接受新连接。使用阻塞方式,调用 BluetoothServerSocket.accept()
    private class AcceptThread extends Thread {
        private final BluetoothServerSocket mmServerSocket;

        public AcceptThread() {
            BluetoothServerSocket tmp = null;
            try {
                //使用射频端口(RF comm)监听
                tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
            } catch (IOException e) {
            }
            mmServerSocket = tmp;
        }

        @Override
        public void run() {
            setName("AcceptThread");
            BluetoothSocket socket = null;
            while (mState != STATE_CONNECTED) {
                try {
                    socket = mmServerSocket.accept();
                } catch (IOException e) {
                    break;
                }
                if (socket != null) {
                    synchronized (ChatService.this) {
                        switch (mState) {
                            case STATE_LISTEN:
                            case STATE_CONNECTING:
                                connected(socket, socket.getRemoteDevice());
                                break;
                            case STATE_NONE:
                            case STATE_CONNECTED:
                                try {
                                    socket.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                break;
                        }
                    }
                }
            }
        }

        public void cancel() {
            try {
                mmServerSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*
        连接线程,专门用来对外发出连接对方蓝牙的请求和处理流程。
        构造函数里通过 BluetoothDevice.createRfcommSocketToServiceRecord() ,
        从待连接的 device 产生 BluetoothSocket. 然后在 run 方法中 connect ,
        成功后调用 BluetoothChatSevice 的 connected() 方法。定义 cancel() 在关闭线程时能够关闭相关socket 。
     */
    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;

        public ConnectThread(BluetoothDevice device) {
            mmDevice = device;
            BluetoothSocket tmp = null;
            try {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
                e.printStackTrace();
            }
            mmSocket = tmp;
        }

        @Override
        public void run() {
            setName("ConnectThread");
            mAdapter.cancelDiscovery();
            try {
                mmSocket.connect();
            } catch (IOException e) {
                connectionFailed();
                try {
                    mmSocket.close();
                } catch (IOException e2) {
                    e.printStackTrace();
                }
                ChatService.this.start();
                return;
            }
            synchronized (ChatService.this) {
                mConnectThread = null;
            }
            connected(mmSocket, mmDevice);
        }

        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*
        双方蓝牙连接后一直运行的线程;构造函数中设置输入输出流。
        run()方法中使用阻塞模式的 InputStream.read()循环读取输入流,然后发送到 UI 线程中更新聊天消息。
        本线程也提供了 write() 将聊天消息写入输出流传输至对方,传输成功后回写入 UI 线程。最后使用cancel()关闭连接的 socket
     */
    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        @Override
        public void run() {
            byte[] buffer = new byte[1024];
            int bytes;
            while (true) {
                try {
                    bytes = mmInStream.read(buffer);
                    mHandler.obtainMessage(weixinFragment.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
                } catch (IOException e) {
                    connectionLost();
                    break;
                }
            }
        }

        public void write(byte[] buffer) {
            try {
                mmOutStream.write(buffer);
                mHandler.obtainMessage(weixinFragment.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

创建一个新的Activity:
DeviceList.java:
实现选取与之会话的蓝牙设备。供菜单项主界面的选项菜单“我的友好”调用,用于:(1)显示已配对的好友列表;(2)搜索可配对的好友进行配对;(3)新选择并配对的蓝牙设备将刷新好友列表。
发现新的蓝牙设备并请求配对时,需要对应接受。
部分代码:

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                if (mNewDevicesArrayAdapter.getCount() == 0) {
                    String noDevices = getResources().getText(R.string.none_found).toString();
                    mNewDevicesArrayAdapter.add(noDevices);
                }
            }
        }
    };
    private void init() {
        Button scanButton = findViewById(R.id.button_scan);
        scanButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(DeviceList.this, R.string.scanning, Toast.LENGTH_LONG).show();
                doDiscovery();  //搜索蓝牙设备
            }
        });
        mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
        mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
        //已配对蓝牙设备列表
        ListView pairedListView =findViewById(R.id.paired_devices);
        pairedListView.setAdapter(mPairedDevicesArrayAdapter);
        pairedListView.setOnItemClickListener(mPaireDeviceClickListener);
        //未配对蓝牙设备列表
        ListView newDevicesListView = findViewById(R.id.new_devices);
        newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
        newDevicesListView.setOnItemClickListener(mNewDeviceClickListener);
        //动态注册广播接收者
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver, filter);
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
            for (BluetoothDevice device : pairedDevices) {
                mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            }
        } else {
            String noDevices = getResources().getText(R.string.none_paired).toString();
            mPairedDevicesArrayAdapter.add(noDevices);
        }
    }

weixinFragment.java:
注意在Fragment中使用toolbar,每一次都会在初始化fragment时都会调用 ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar),但如果是几个fragment在一个activity上的,那么toolbar可能会bug,比如设置menu菜单不显示。
解决方法是:
在findViewById后直接调用toolbar自带的方法来处理menu显示点击问题即可,无需调用((AppCompatActivity) getActivity()).setSupportActionBar(toolbar)为fragment设置toolbar。
//不加这行菜单无法显示,告诉fragment我们有菜单的
setHasOptionsMenu(true);
//加载菜单
mToolbar.inflateMenu(R.menu.market_menu);
所以在onCreateView中部分代码:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view= inflater.inflate(R.layout.tab01, container, false);

        Toolbar toolbar = view.findViewById(R.id.toolbar);
        setHasOptionsMenu(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            }
        }

        //创建选项菜单
        toolbar.inflateMenu(R.menu.option_menu);
        //选项菜单监听
        toolbar.setOnMenuItemClickListener(new MyMenuItemClickListener());
        mTitle = view.findViewById(R.id.title_left_text);
        mTitle.setText(R.string.app_name);
        mTitle = view.findViewById(R.id.title_right_text);
        // 得到本地蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Toast.makeText(view.getContext(), "蓝牙不可用", Toast.LENGTH_LONG).show();
            getActivity().finish();
            return view;
        }
        if (!mBluetoothAdapter.isEnabled()) { //若当前设备蓝牙功能未开启
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT); //
        } else {
            if (mChatService == null) {
                setupChat();  //创建会话
            }
        }

        return view;
    }
蓝牙聊天功能使用说明:

1.把AS中的项目在实际的两部手机中运行,如果未打开手机蓝牙,则进入打开蓝牙设置界面;
(AS项目在实际手机运行可使用Android WiFi ADB)
使用教程: Androi WiFi ADB使用.
2.在右上角三点,选择“我的好友”,即可看到已经匹配成功的的蓝牙设备,直接点击,进行会话;
3.新建好友前,需要先使用选项菜单“设置在线”,即要求对方可见(能被扫描到)。然后,单击“搜索好友”按钮。即可找到还未匹配的设备,从而进行匹配。
最后附上源码(码云仓库):
链接: https://gitee.com/yangjy11/AS-WeChatBluetooth/tree/master/WeiXinApplication/app/src/main.

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值