蓝牙鼠标测试代码 Android

蓝牙鼠标测试代码在Android平台上可以使用以下步骤实现:

  1. 首先,需要在AndroidManifest.xml文件中添加蓝牙权限和蓝牙设备扫描权限:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
2.创建一个BluetoothAdapter对象,用于管理蓝牙设备的连接和发现:
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
3.检查蓝牙是否可用:
if (bluetoothAdapter == null) {
    Toast.makeText(this, "蓝牙不可用", Toast.LENGTH_SHORT).show();
    finish();
    return;
}

4.开始扫描附近的蓝牙设备:

bluetoothAdapter.startDiscovery();

5.注册一个BroadcastReceiver来接收蓝牙设备发现的广播: 

private final BroadcastReceiver receiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // 在这里处理找到的蓝牙设备,例如将其添加到列表中
        }
    }
};

 6.在onResume()方法中注册BroadcastReceiver,并在onPause()方法中注销BroadcastReceiver:

@Override
protected void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(receiver, filter);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(receiver);
}

7.当用户点击按钮时,尝试连接到指定的蓝牙设备:

private void connectToDevice(BluetoothDevice device) {
    if (device == null) {
        Toast.makeText(this, "未找到蓝牙设备", Toast.LENGTH_SHORT).show();
        return;
    }
    UUID uuid = StandardUUIDs.UUID_SERVICE_CLASS_BLUETOOTH_MOUSE;
    BluetoothGatt gatt = device.connectGatt(this, false, gattCallback);
}
8.创建一个BluetoothGattCallback对象来处理蓝牙设备的连接状态和数据接收:
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            // 连接成功,可以开始读取和写入数据
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            // 连接断开,需要重新连接或释放资源
        }
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        // 处理读取到的数据
    }

    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        // 处理写入操作的结果
    }
};

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Android Java 蓝牙测试代码,可以用于搜索和连接蓝牙设备: ```java import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.io.IOException; import java.util.ArrayList; import java.util.Set; import java.util.UUID; public class MainActivity extends AppCompatActivity { private BluetoothAdapter bluetoothAdapter; private ListView listView; private ArrayAdapter<String> adapter; private ArrayList<BluetoothDevice> devices; private ConnectThread connectThread; private ConnectedThread connectedThread; private Handler handler; private static final int MESSAGE_READ = 1; private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 初始化蓝牙适配器 bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // 初始化ListView和Adapter listView = (ListView) findViewById(R.id.listView); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, 0); listView.setAdapter(adapter); // 初始化设备列表 devices = new ArrayList<BluetoothDevice>(); // 初始化Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MESSAGE_READ: byte[] readBuf = (byte[]) msg.obj; String readMessage = new String(readBuf, 0, msg.arg1); // 处理接收到的数据 break; } } }; // 检查蓝牙是否可用 if (bluetoothAdapter == null) { Toast.makeText(this, "蓝牙不可用", Toast.LENGTH_SHORT).show(); } else { // 检查蓝牙是否已经开启 if (!bluetoothAdapter.isEnabled()) { // 请求开启蓝牙 BluetoothAdapter.enable(); } // 显示已配对设备 Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { devices.add(device); adapter.add(device.getName() + "\n" + device.getAddress()); } } } } @Override protected void onDestroy() { super.onDestroy(); // 关闭连接线程和数据传输线程 if (connectThread != null) { connectThread.cancel(); connectThread = null; } if (connectedThread != null) { connectedThread.cancel(); connectedThread = null; } } // 搜索蓝牙设备 private void searchDevices() { // 开始搜索 bluetoothAdapter.startDiscovery(); } // 停止搜索蓝牙设备 private void stopSearch() { // 停止搜索 bluetoothAdapter.cancelDiscovery(); } // 连接蓝牙设备 private void connectDevice(BluetoothDevice device) { // 开始连接 connectThread = new ConnectThread(device); connectThread.start(); } // 发送数据 private void sendData(byte[] data) { // 发送数据 connectedThread.write(data); } // 连接线程 private class ConnectThread extends Thread { private BluetoothSocket socket; private BluetoothDevice device; public ConnectThread(BluetoothDevice device) { this.device = device; try { // 创建一个Socket连接 socket = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { // 连接 try { socket.connect(); } catch (IOException e) { e.printStackTrace(); try { // 关闭Socket socket.close(); } catch (IOException e1) { e1.printStackTrace(); } return; } // 连接成功,启动数据传输线程 connectedThread = new ConnectedThread(socket); connectedThread.start(); } public void cancel() { try { // 关闭Socket socket.close(); } catch (IOException e) { e.printStackTrace(); } } } // 数据传输线程 private class ConnectedThread extends Thread { private BluetoothSocket socket; private byte[] buffer; private int bytes; public ConnectedThread(BluetoothSocket socket) { this.socket = socket; buffer = new byte[1024]; } @Override public void run() { // 循环接收数据 while (true) { try { bytes = socket.getInputStream().read(buffer); handler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget(); } catch (IOException e) { e.printStackTrace(); break; } } } public void write(byte[] data) { try { // 发送数据 socket.getOutputStream().write(data); } catch (IOException e) { e.printStackTrace(); } } public void cancel() { try { // 关闭Socket socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } ``` 注意:需要在 AndroidManifest.xml 文件中添加以下权限: ```xml <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值