在android上通过蓝牙发送对象,如何序列化对象并发送?

时间:2013-03-21 00:35:41

标签: android bluetooth

我已经阅读了大量的SO线程,我仍然感到困惑。我需要发送一个舰船对象,用于战舰游戏。我已经使船类实现了serializable,但我似乎无法发送该对象。我基本上只使用了我在网上找到的代码并将其纳入我的connectedThread代码(与android dev网站相同)。代码如下。谁能告诉我哪里出错了,非常感谢任何帮助。当我运行代码时出现错误,这似乎来自于objectinputstream端

public class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    private ObjectOutput out = null;
    byte[] yourBytes = new byte[1024];

    public ConnectedThread(BluetoothSocket socket) {
        Log.d(TAG, "connectedthread started");
        // mHandler.obtainMessage(TEST).sendToTarget();
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        yourBytes = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {

            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
            out = new ObjectOutputStream(bos);

        } 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();

                Log.i(TAG, "READ OBJECT");
                    // ........................................THIS IS CODE THAT HAS ERRORS-----------
                    ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
                    ObjectInput in = null;
                    try {
                        in = new ObjectInputStream(mmInStream);
                        Ship yourObject = (Ship) in.readObject();
                        //Log.i("Object received maybe", yourObject.toString());
                        if(yourObject!=null)
                        mHandler.obtainMessage(SetUpGame.MESSAGE_READ_OBJ, -1, -1, yourObject).sendToTarget();
                    } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {
                        bis.close();
                        in.close();
                    }

 // -----------------------------------IF I DELETE THE ABOVE CODE IT WORKS FOR STRINGS PERFECTLY------
                }

            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");
        }
    }

    public void writeObj(Ship ship) {
        bos = new ByteArrayOutputStream();
        ObjectOutput out = null;
        try {
            out = new ObjectOutputStream(mmOutStream);
            out.writeObject(ship);
            yourBytes = bos.toByteArray();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
            out.close();
            bos.close();
        } catch (IOException e) {
            Log.e(TAG, "close of connect socket failed");
        }
    }

}

和logcat:

03-21 02:41:41.594: E/AndroidRuntime(12529): java.lang.NullPointerException
03-21 02:41:41.594: E/AndroidRuntime(12529):    at java.io.ByteArrayInputStream.<init>(ByteArrayInputStream.java:58)
03-21 02:41:41.594: E/AndroidRuntime(12529):    at com.example.battleships.v2.ChatService$ConnectedThread.run(ChatService.java:280)
03-21 02:41:41.875: E/ActivityThread(12529): Activity com.example.battleships.v2.MainScreen has leaked IntentReceiver com.example.battleships.v2.MainScreen$2@40521320 that was originally registered here. Are you missing a call to unregisterReceiver()?
03-21 02:41:41.875: E/ActivityThread(12529): android.app.IntentReceiverLeaked: Activity com.example.battleships.v2.MainScreen has leaked IntentReceiver com.example.battleships.v2.MainScreen$2@40521320 that was originally registered here. Are you missing a call to unregisterReceiver()?
03-21 02:41:41.875: E/ActivityThread(12529):    at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:799)
03-21 02:41:41.875: E/ActivityThread(12529):    at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:575)
03-21 02:41:41.875: E/ActivityThread(12529):    at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:865)
03-21 02:41:41.875: E/ActivityThread(12529):    at android.app.ContextImpl.registerReceiver(ContextImpl.java:852)
03-21 02:41:41.875: E/ActivityThread(12529):    at android.app.ContextImpl.registerReceiver(ContextImpl.java:846)
03-21 02:41:41.875: E/ActivityThread(12529):    at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:318)
03-21 02:41:41.875: E/ActivityThread(12529):    at com.example.battleships.v2.MainScreen.setUpUI(MainScreen.java:167)
03-21 02:41:41.875: E/ActivityThread(12529):    at com.example.battleships.v2.MainScreen.onCreate(MainScreen.java:160)
03-21 02:41:41.875: E/ActivityThread(12529):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1072)
03-21 02:41:41.875: E/ActivityThread(12529):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1836)
03-21 02:41:41.875: E/ActivityThread(12529):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1893)

1 个答案:

答案 0 :(得分:0)

看起来你已经通过在方法writeObj()中重新声明它来重写类变量“out”。删除“ObjectOutput out = null;”来自writeObj()。

当你继续重置类变量“bos”时,你似乎有点不确定要写入哪个流。

你可能会得到一个NullPointerException,因为你试图以你认为的方式使用不在范围内的变量。