你好
我有一个疯狂的想法,试图以编程方式从我的Android设备连接到我的Apple AirPods,并尝试“记录”传入的信号(例如,当AirPod连按两次,从耳朵拿出,电池报告等时)。 ) 由于我之前从未尝试过任何Android蓝牙产品,因此我研究了一些文档,观看了一些教程并编写了以下代码:
//In my main activity, this gets called when my AirPods have been successfully connected to my Android device
private void connectedToDevice(BluetoothDevice device)
{
mLog("Attempting to read data...");
BTConnectionService mConnection = new BTConnectionService();
}
这是BTConnectionService
类:
private static final UUID MY_UUID = UUID.fromString("0000110E-0000-1000-8000-00805F9B34FB");
private final BluetoothAdapter mBluetoothAdapter;
private AcceptThread mAcceptThread;
private ConnectedThread mConnectedThread;
public BTConnectionService(Context context)
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
start();
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mServerSocket;
public AcceptThread()
{
BluetoothServerSocket tmp = null;
try
{
tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(APP_NAME, MY_UUID);
Log.d(TAG, "AcceptThread: BluetoothServerSocket established.");
}
catch (IOException e) { e.printStackTrace(); }
mServerSocket = tmp;
}
public void run()
{
BluetoothSocket socket = null;
try { socket = mServerSocket.accept();
Log.d(TAG, "run: mServerSocket.accept()"); }
catch (IOException e) { e.printStackTrace(); cancel(); }
if(socket != null)
{
mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();
}
}
public void cancel()
{
try { mServerSocket.close(); } catch (IOException e) { e.printStackTrace(); }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mSocket;
private final InputStream mInStream;
public ConnectedThread(BluetoothSocket socket)
{
mSocket = socket;
InputStream tmpIn = null;
try { tmpIn = mSocket.getInputStream(); }
catch (IOException e) {e.printStackTrace();}
mInStream = tmpIn;
Log.d(TAG, "ConnectedThread: set up");
}
public void run()
{
byte[] buffer = new byte[1024];
int bytes; //bytes returned from read()
while(true)
{
try
{
bytes = mInStream.read(buffer);
Log.d(TAG, "READ: " + bytes);
}
catch (IOException e) { break; }
}
}
}
public synchronized void start()
{
Log.d(TAG, "BTConnectionService started.");
if(mAcceptThread == null)
{
mAcceptThread = new AcceptThread();
mAcceptThread.start();
}
}
我的问题是mServerSocket.accept()
从不返回任何内容。我是否必须以某种方式将传递给listenUsingInsecureRfcommWithServiceRecord
方法的“名称”和“ uuid”与目标设备进行匹配,否则我做错了什么?我对此很陌生。我的代码对我来说似乎太模糊了,根本没有考虑连接的设备,但这是我唯一可以在网上找到的东西。预先非常感谢。