我正在制作一个战舰游戏,我想发送一个名为 Ships 的类的数组(其中包含船名、大小、旋转与否等内容以及坐标的数组列表)。我用谷歌搜索了这个并查看了堆栈溢出,我基本上需要序列化数组,但这就是我卡住的地方。我需要使用 ObjectOutputStream,但是如何将其合并到下面的代码中(取自 android 开发站点)。注意我已经使船类实现可序列化。提前致谢
public class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "connectedthread started");
// mHandler.obtainMessage(TEST).sendToTarget();
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created");
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "Begin mConnectedThread");
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
Log.i(TAG, "reaaaad msg");
mHandler.obtainMessage(SetUpGame.MESSAGE_READ2, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnectd");
break;
}
}
}
/*
* Call this from the main activity to send data to the remote
* device
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
Log.i(TAG, "writeeee msg");
mHandler.obtainMessage(SetUpGame.MESSAGE_WRITE, -1,-1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write");
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close of connect socket failed");
}
}
}
和我的处理程序:
final Handler mHandler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case MESSAGE_READ2:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
//Toast.makeText(getApplicationContext(),"Me:" + writeMessage, Toast.LENGTH_SHORT).show();
break;