Android 蓝牙聊天程序的实现

1.接收蓝牙客户端请求的AcceptThread
   <pre name="code" class="java"> private class AcceptThread extends Thread {
        private BluetoothServerSocket serverSocket;
        BluetoothSocket socket;
        private InputStream inputStream;
        private OutputStream os;

        public AcceptThread() {
            try {
                //创建BluetoothServerSocket对象
                serverSocket=bluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME,MY_UUID);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try {
                //等待接收蓝牙客户端的请求
                socket=serverSocket.accept();
                inputStream=socket.getInputStream();
                os=socket.getOutputStream();
                //通过循环不断接收客户端发过来的数据,如果客户端暂时没发数据,则read方法处于阻塞状态
                while (true){
                    byte[] bytes=new byte[1024];
                    int count=inputStream.read(bytes);
                    //发送消息通知
                    Message message=new Message();
                    message.obj=new String(bytes,0,count,"utf-8");
                    handler.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
 

2.单击蓝牙设备列表发送消息

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //获取Mac地址
                String string = bluetoothDevices.get(position);
                String address=string.substring(string.indexOf(":")+1).trim();
                if (bluetoothAdapter.isDiscovering()){
                    bluetoothAdapter.cancelDiscovery();
                }
                if (device==null){
                    //获取蓝牙地址,相当于网络客户端Socket指定IP地址
                    device=bluetoothAdapter.getRemoteDevice(address);
                }
                if (clientSocket==null){
                    try {
                        //通过UUID连接蓝牙设备,相当于网络客户端Socket指定端口号
                        clientSocket=device.createRfcommSocketToServiceRecord(MY_UUID);
                        //连接蓝牙设备并获取向服务端发送数据的OutputStream对象
                        clientSocket.connect();
                        outputStream=clientSocket.getOutputStream();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (outputStream!=null){
                    try {
                        String text=editText.getText().toString();
                        if ("".equals(text)){
                            Toast.makeText(BluetoothActivity.this, "发送内容不能为空!",
                                    Toast.LENGTH_LONG).show();
                            return;
                        }
                        outputStream.write(text.getBytes("utf-8"));
                        Toast.makeText(BluetoothActivity.this, "发送信息成功",
                                Toast.LENGTH_LONG).show();
                    } catch (IOException e) {
                        Toast.makeText(BluetoothActivity.this, "发送信息失败",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }
              }
        });
3.扫描蓝牙设备
 BroadcastReceiver broadcastReceiver=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) {
                    bluetoothDevices.add(device.getName()+":"+device.getAddress());
                    arrayAdapter.notifyDataSetChanged();
                }
            }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
            {
                setProgressBarIndeterminateVisibility(false);
                setTitle("连接蓝牙设备");

            }
        }
    };
4.处理获得消息

 Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {

            Toast.makeText(BluetoothActivity.this, String.valueOf(msg.obj),
                    Toast.LENGTH_LONG).show();
            super.handleMessage(msg);
        }
    };
5.初始化变量及注册监听

 ListView listView;
    BluetoothAdapter bluetoothAdapter;
    List<String> bluetoothDevices;
    ArrayAdapter<String> arrayAdapter;
    private final UUID MY_UUID = UUID
            .fromString("db764ac8-7f26-4b08-aafe-59d03c27bae3");
    private final String NAME = "Bluetooth_Socket";
    AcceptThread acceptThread;
    BluetoothDevice device;
    BluetoothSocket clientSocket;
    OutputStream outputStream;
    Button button;
    EditText editText;

  bluetoothDevices=new ArrayList<>();
        bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
        bluetoothAdapter.enable();
        listView=(ListView)findViewById(R.id.listView);
        Set<BluetoothDevice> bluetoothDeviceSet=bluetoothAdapter.getBondedDevices();
        button=(Button)findViewById(R.id.button);
        editText=(EditText)findViewById(R.id.editText);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setProgressBarIndeterminateVisibility(true);
                setTitle("正在扫描...");

                if (bluetoothAdapter.isDiscovering())
                {
                    bluetoothAdapter.cancelDiscovery();
                }
                bluetoothAdapter.startDiscovery();
            }
        });
        if (bluetoothDeviceSet.size()>0) {
            for (BluetoothDevice device:bluetoothDeviceSet){
                bluetoothDevices.add(device.getName()+":"+device.getAddress());
            }
        }
    
        acceptThread=new AcceptThread();
        acceptThread.start();
        registerReceiver(broadcastReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
        registerReceiver(broadcastReceiver,new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
  

6.布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_bluetooth"
    tools:context="com.gst.user.application.BluetoothActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="搜索"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_below="@+id/button"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:allowUndo="true"
        android:hint="在此处输入发送的内容"
        android:layout_above="@+id/listView"
        android:layout_toRightOf="@+id/button"
        android:layout_toEndOf="@+id/button" />

</RelativeLayout>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值