蓝牙连接

本文介绍了一种基于Android平台的蓝牙连接方案,详细展示了客户端和服务端的实现过程。客户端部分通过按钮控制蓝牙的开启、关闭、搜索和配对,能够与服务端建立连接并发送消息;服务端则监听连接请求,接收并处理来自客户端的消息。

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

客户端

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private UUID uuid = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");
    private String[] premissons = new String[]{
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
    };
    public static final int REQUEST_CODE = 101;
    public static final int OPEN_CODE = 102;

    private List<BluetoothDevice> list_bond = new ArrayList<>();
    private List<BluetoothDevice> list_dis = new ArrayList<>();

    private MyAdapter adapter_bond;
    private MyAdapter adapter_dic;

    private BluetoothManager bluetoothManager;
    private BluetoothAdapter bluetoothAdapter;
    private MyRecevice myRecevice;

    private Button bt_open;
    private Button bt_close;
    private Button bt_discovery;
    private Button bt_bond;
    private ListView listView_discovery;
    private ListView listView_bond;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestPermissions(premissons,REQUEST_CODE);
        initView();
        //获得本地蓝牙设备
        bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        //注册广播
        myRecevice = new MyRecevice();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        registerReceiver(myRecevice,intentFilter);
    }
    //解除注册
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myRecevice);
    }

    private void initView() {
        bt_open = (Button) findViewById(R.id.bt_open);
        bt_close = (Button) findViewById(R.id.bt_close);
        bt_discovery = (Button) findViewById(R.id.bt_discovery);
        bt_bond = (Button) findViewById(R.id.bt_bond);
        listView_discovery = (ListView) findViewById(R.id.listView_discovery);
        listView_bond = (ListView) findViewById(R.id.listView_bond);

        bt_open.setOnClickListener(this);
        bt_close.setOnClickListener(this);
        bt_discovery.setOnClickListener(this);
        bt_bond.setOnClickListener(this);
        //附近设备
        adapter_dic = new MyAdapter(list_dis,this);
        listView_discovery.setAdapter(adapter_dic);
        //已配对设备
        adapter_bond = new MyAdapter(list_bond,this);
        listView_bond.setAdapter(adapter_bond);

        listView_discovery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                BluetoothDevice device = list_dis.get(i);
                device.createBond();
            }
        });
        listView_bond.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                BluetoothDevice device = list_bond.get(i);
                try {
                    BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
                    socket.connect();
                    if (socket.isConnected()){
                        socket.getOutputStream().write("大金牙正在和你配对".getBytes());
                    }else {
                        Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (IOException e) {
                    Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_open:
                Intent intent = new Intent();
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);//可用
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//可被扫描
                intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,120);
                startActivityForResult(intent,OPEN_CODE);
                break;
            case R.id.bt_close:
                bluetoothAdapter.disable();
                break;
            case R.id.bt_discovery:
                list_dis.clear();
                bluetoothAdapter.startDiscovery();
                break;
            case R.id.bt_bond:
                list_bond.clear();
                Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
                list_bond.addAll(bondedDevices);
                adapter_bond.notifyDataSetChanged();
                break;
        }
    }
    class MyRecevice extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){
               BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
               list_dis.add(bluetoothDevice);
               adapter_dic.notifyDataSetChanged();
            }
        }
    }
}

服务端

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private UUID uuid = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");
    private Button button;
    private ImageView imageView;

    private BluetoothManager manager;
    private BluetoothAdapter adapter;

    private String [] premissons = new String[]{
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
    };
    public static final int REQUEST_CODE = 101;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestPermissions(premissons,REQUEST_CODE);
        manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        adapter = manager.getAdapter();
        initView();
    }

    private void initView() {
        button = (Button) findViewById(R.id.button);
        imageView = (ImageView) findViewById(R.id.imageView);

        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                try {
                    BluetoothServerSocket serverSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(adapter.getName(), uuid);
                    BluetoothSocket socket = serverSocket.accept();
                    Toast.makeText(this, socket.getRemoteDevice().getName()+"连接上了", Toast.LENGTH_SHORT).show();
                    InputStream is = socket.getInputStream();
                    byte b[] = new byte[1024];
                    int read = is.read(b);
                    String string = new String(b,0,read);
                    Toast.makeText(this, ""+string, Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }


                break;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值