Friday, July 24, 2015

7.24

为了从蓝牙这传输数据,我从昨天下午到今天三点,整了个头疼欲裂。
基本上数据是能搞定了,不过还有一些别的问题,诸如消息不对称问题等。

 send的逻辑



public void write(byte[] out) { // Create temporary object ConnectedThread r; // Synchronize a copy of the ConnectedThread synchronized (this) { if (mState != STATE_CONNECTED) { return; } r = mConnectedThread; } r.write(out); }











// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket, socketType);
mConnectedThread.start(); 

 
public boolean sendMessage(Context context, int[][] message) {
    // Check that we're actually connected before trying anything
    if (mBluetoothService.getState() != BluetoothService.STATE_CONNECTED) {
        Toast.makeText(context, R.string.not_connected, Toast.LENGTH_SHORT)
        .show();
        return false;
    }
    byte[] send = int2byte(message);
    mBluetoothService.write(send);
    return true;
}


因为write的参数只能是byte[], 所以我就直接把int[][]变成byte[] 来发送了 

    public static byte[] int2byte(int[][] data) {
        Log.i("sy__test", "int2byte : "+data.length);
        ByteBuffer byteBuffer = ByteBuffer.allocate((data.length) * (data.length));
        byte[] target = new byte[data.length * 4];
        for (int i = 0; i < data.length; i++) {
            for (int j = 0; j < data[i].length; j++) {
                byteBuffer.put((byte) data[i][j]);
            }
        }
        target = byteBuffer.array();
        return target;
    }


    public static int[][] Byte2Int(byte[] data){   
        IntBuffer intBuffer = IntBuffer.allocate(11);
        int target[][] = new int[intBuffer.limit()][intBuffer.limit()];
        Log.i("sy__test", "intBuffer.limit() = "+intBuffer.limit());
        int j=0;
        for (int i = 0; i < 121; i++) {
            Log.i("sy__test", "data.length = "+data.length+", data[i]= "+data[i]);
                intBuffer.put(data[i]);
//                intBuffer = ByteBuffer.wrap(data).asIntBuffer();
                if ((i+1)%11 == 0) {
                    target[j] = intBuffer.array().clone();
                    j++;
                    intBuffer.clear();
                }
        }
        return target;
    }


 

No comments:

Post a Comment