蓝牙

本文详细介绍了一个蓝牙应用程序的开发过程,包括如何使用Android系统提供的API来实现蓝牙设备的搜索、连接及数据传输等功能。文章通过具体代码展示了如何创建蓝牙服务器与客户端,并实现两者之间的通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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








package alice.bw.com.day04_yuekaodemo;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class BluetoothActivity extends AppCompatActivity implements View.OnClickListener {
    public static final String TAG = "ABCDE";
    private List<String> dataSource  = new ArrayList<>();
    private TextView devices_list;
    private BluetoothAdapter bluetoothAdapter;
    private Set<BluetoothDevice> bondedDevices;
    private TextView searchBlueTooth;
    private ListView bluetooth_devices_list;
    //第二部开启广播并且进行获取周边蓝牙并输出到TextView
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            bluetoothAdapter.isEnabled();
            String action = intent.getAction();
            //获取已经搜索到的设备
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice bluetoothDevice = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (/*bluetoothDevice.getBondState() != BluetoothDevice.BOND_BONDED*/true) {
                    String address = bluetoothDevice.getAddress();//获取蓝牙的MAC地址
                    String name = bluetoothDevice.getName();//获取蓝牙的名称
                    String name_address= name + ":" + address;
                    dataSource.add(name_address);
                    //                    devices_list.append(name + ":" + address + "\n");//将蓝牙的地址和名称设置到TextView上
                }
            } else if (bluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                devices_list.append("搜索完毕");
                MyListViewAdapter  myListViewAdapter = new MyListViewAdapter(BluetoothActivity.this,dataSource);
                bluetooth_devices_list.setAdapter(myListViewAdapter);

            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        //启动子线程创建蓝牙服务器


        IntentFilter intentFilter = new IntentFilter();//广播接收者的过滤器
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);//添加
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//添加发现蓝牙设备的action动作
        intentFilter.addAction(bluetoothAdapter.ACTION_DISCOVERY_FINISHED);//扫描蓝牙设备完毕
        this.registerReceiver(receiver, intentFilter);//注册蓝牙广播

        //第一步打开蓝牙并且将获取到的信息输出
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//获取蓝牙适配器
        bondedDevices = bluetoothAdapter.getBondedDevices();//将搜索到的蓝牙设备放入Set集合中
       /* for (BluetoothDevice device : bondedDevices) {
            String address = device.getAddress();//获取蓝牙的MAC地址
            String name = device.getName();//获取蓝牙的名称
            devices_list.append(name + ":" + address + "\n");//将蓝牙的地址和名称设置到TextView上

        }*/

        BluetoothServerSocketThread bluetoothServerSocketThread = new BluetoothServerSocketThread();
        bluetoothServerSocketThread.start();//开启子线程


    }

    //第三部进行实例化
    private void initView() {
        devices_list = (TextView) findViewById(R.id.devices_list);
        searchBlueTooth = (TextView) findViewById(R.id.searchBlueTooth);
        searchBlueTooth.setOnClickListener(this);
        bluetooth_devices_list = (ListView) findViewById(R.id.bluetooth_devices_list);


        //为ListView添加点击事件,事件的具体内容上是建立蓝牙客户端,客户端给服务器发送一条消息
        bluetooth_devices_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            String TAG = "ABCDE";

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i(TAG,"0");
                String devices_name_addresss = dataSource.get(position);//从扫描到的蓝牙设备中拿到蓝牙设备的地址和名称
                Log.i(TAG,"1");
                //   bw:11.22222.444
                String devices_addresss = devices_name_addresss.substring(devices_name_addresss.indexOf(":") + 1);
                Log.i(TAG,"2");
                //getRemoteDevice(String address)
                //通过蓝牙设备的地址创建蓝牙设备
                BluetoothDevice remoteDevice = bluetoothAdapter.getRemoteDevice(devices_addresss);
                Log.i(TAG,"3");
                // createRfcommSocketToServiceRecord(UUID uuid)
                UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
                Log.i(TAG,"4");
                try {
                    //根据已经创建的蓝牙设备创建一个该蓝牙设备的客户端,这里的uuid相当于是一个IP地址,通过地址就可以找到服务器
                    BluetoothSocket devicesClient = remoteDevice.createRfcommSocketToServiceRecord(uuid);
                    Log.i(TAG,"5");
                    devicesClient.connect();//链接到蓝牙服务器
                    Log.i(TAG,"6");

                    OutputStream outputStream = devicesClient.getOutputStream();
                    Log.i(TAG,"7");
                    outputStream.write("发送信息到蓝牙设备".getBytes());
                    Log.i(TAG,"8");
                    outputStream.flush();
                    Log.i(TAG,"9");


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });



    }


    //点击搜索周围的蓝牙
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.searchBlueTooth://点击按钮开始搜索周边的蓝牙

                if (bluetoothAdapter.isDiscovering()) {//如果正在搜索蓝牙就停止搜索
                    bluetoothAdapter.cancelDiscovery();
                }
                bluetoothAdapter.startDiscovery();//使用蓝牙适配器搜索周边蓝牙
                break;
        }
    }

    //自定义一个展示发现的蓝牙设备的LListView控件的适配器
    class MyListViewAdapter extends BaseAdapter {

        private Context context;
        private List<String> dataSource ;

        public MyListViewAdapter(Context context, List<String> dataSource) {
            this.context = context;
            this.dataSource = dataSource;
        }

        @Override
        public int getCount() {//获取item条目的个数
            return dataSource.size();
        }

        @Override
        public Object getItem(int position) {
            return dataSource.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(context);
                convertView = inflater.inflate(R.layout.list_item, null);
            }
            TextView item = (TextView) convertView.findViewById(R.id.item);
            item.setText(dataSource.get(position));
            return convertView;
        }
    }

    private class BluetoothServerSocketThread extends Thread {
        private BluetoothServerSocket bluetoothServerSocket;
        private BluetoothSocket clientSocket;
        private InputStream inputStream;
        private OutputStream outputStream;

        public BluetoothServerSocketThread( ) {
            //listenUsingRfcommWithServiceRecord(String name, UUID uuid)
            //            UUID uuid = UUID.randomUUID();
            try {
                //创建蓝牙服务器,第一个参数是服务器的名称,第二个是一个唯一标识当前服务器的ID,相当于是一个IP地址
                UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
                bluetoothServerSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord("1508a_Service", uuid);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            super.run();
            try {
                clientSocket = bluetoothServerSocket.accept();//监听客户端的链接
                inputStream = clientSocket.getInputStream();
                outputStream = clientSocket.getOutputStream();


                while (true) {

                    byte[] buffer = new byte[1024];
                    int count = inputStream.read(buffer);
                    String message = new String(buffer, 0, count, "utf-8");
                    Looper.prepare();
                    Toast.makeText(BluetoothActivity.this,message,Toast.LENGTH_LONG).show();
                    Looper.loop();

                }



            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值