私はArduinoで作られたアラームシステムを扱うAndroidアプリケーションを開発しています。 ArduinoからInputStreamを処理し、ArduinoからOutputStreamを処理する必要があります。まず、スレッドを使用してBluetoothソケットの接続を初期化して動作させましたが、スレッド内でArduinoからのストリームを処理できるようなサービス/スレッドを呼び出す必要がありましたが、それをやる。 実際には、仮説的なサービスはストリームがあれば継続的に聴取しなければならず、一定の時間が経過してからでなく、いつでも停止する必要があります。助けてくれてありがとう!ここではBluetoothのソケット接続に関連するコードは次のとおりです。AndroidでBluetooth経由でInputStreamとOutputStreamを処理する方法
public class ConnectThread extends Thread {
private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
while (!Thread.currentThread().isInterrupted()) {
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
Log.i("Log", "Socket closed");
this.interrupt();
Log.i("Log", "Thread interrupted");
} catch (IOException closeException) {
}
}
//I think here I have to start a sort of Service/Thread..
}
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
this.interrupt();
Log.i("Log", "Thread interrupted");
} catch (IOException e) { }
}
}