Bluetooth センサーからデータを受信するアプリケーションに取り組んでおり、ローカル マシンで実行されているサーバー ソケットにそのデータを渡す必要があります。受信されるデータは、1 秒あたり約 40 メッセージです。
まず、書き込みごとに個別の AsyncTask を使用し、ソケットを開き、データを書き込み、ソケットを閉じて解決しようとしましたが、問題なく動作しましたが、パフォーマンスの問題が発生したため、別の解決策を見つける必要がありました。
ソケット接続を維持するサービスを作成しましたが、ソケットにデータを書き込もうとすると、書き込みのたびに壊れたパイプの例外が発生し続けます。
サービスのコードは次のとおりです。
public class SocketService extends Service {
public static final String SERVERIP = "10.64.64.197";
public static final int SERVERPORT = 4444;
private DataOutputStream out;
private Socket socket;
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
SocketService getService() {
return SocketService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
Runnable connect = new connectSocket();
new Thread(connect).start();
}
public void sendMessage(byte[] message) {
try {
out.write(message);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
class connectSocket implements Runnable {
@Override
public void run() {
try {
Log.e("connectSocket", "Connecting...");
socket = new Socket(SERVERIP, SERVERPORT);
try {
out = new DataOutputStream(socket.getOutputStream());
Log.e("connectSocket", "Done.");
} catch (Exception e) {
Log.e("connectSocket", "Error", e);
}
} catch (Exception e) {
Log.e("connectSocket", "Error", e);
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
socket = null;
}
そして、sendMessage メソッドを呼び出すコード:
if (action.equals(UartService.ACTION_DATA_AVAILABLE)) {
final byte[] txValue = intent.getByteArrayExtra(UartService.EXTRA_DATA);
try {
mSocketService.sendMessage(txValue);
} catch (Exception e) {
Log.e(TAG, "data_available");
}
}
私はしばらくこれに固執しているので、助けていただければ幸いです!