我正在开发一个应用程序来接收来自蓝牙 Remote 的蓝牙命令。所以要求是每当用户单击一个按钮时,我都应该为该按钮 toast Key_Code
。我试图通过 BluetoothManager
类访问 Bluetooth_Service
,但无法访问该部分。请帮帮我。
获取蓝牙设备的代码:
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
String str = "";
for (BluetoothDevice device : pairedDevices) {
mDevice = device;
str = str+mDevice.getName()+", ";
}
}else{
System.out.println("No devices Found");
}
我正在获取设备名称和 mac 地址等,但没有用于接收命令的 Binder
最佳答案
有两种方法可以做到这一点。
如果你想从你的
Activity
接收android Remote 的KEY_CODES
,你可以直接调用下面的方法。它将为您提供所按下按钮的所有键码。@Override public boolean onKeyDown(int keyCode, KeyEvent event) { Toast.makeText(this,"KeyCode is"+keyCode,Toast.LENGTH_LONG).show(); return super.onKeyDown(keyCode, event); }
注意:Android 服务无法做到这一点。
- 编写一个与您自己的蓝牙服务器连接的蓝牙套接字并开始通信。
客户:
private class ClietnThread extends Thread{
ClietnThread(BluetoothDevice dev){
mDevice= dev;
}
@Override
public void run() {
super.run();
Log.e(Tag,"Now CONNECTING to"+mDevice.getName());
try{
//mBluetoothSocket =(BluetoothSocket) mDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(mDevice,1);
mBluetoothSocket = mDevice.createRfcommSocketToServiceRecord(MY_UUID);
mBluetoothSocket.connect();
}catch (IOException e){
Log.e(Tag,"Connect Failed");
e.printStackTrace();
try {
mBluetoothSocket.close();
} catch (IOException closeException) {
Log.e("Client", "Could not close the client socket", closeException);
}
}
}
}
服务器:
private class MyServer extends Thread{
MyServer(){
}
@Override
public void run() {
super.run();
Log.e(Tag,"Bluetooth Listening");
try {
mBluetoothServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
mBluetoothAdapter.cancelDiscovery();
}catch (IOException e){
e.printStackTrace();
}
while (true){
try{
BluetoothSocket mSoicket = mBluetoothServerSocket.accept();
Log.e(Tag,"ConnectedToSpike");
}catch (IOException e){
e.printStackTrace();
}
}
}
}
关于android - 如何在android中获取连接的蓝牙设备数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42898124/