Android Byte数组

时间:2011-11-28 08:17:58

标签: java android

我从蓝牙发送90000字节数据。我在接收端获得了1024字节的块。我需要在单个数组中收集它们并生成一个字节数组。不能这样做..

这是代码:

    private final Handler mHandler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        System.out.println("***************handleMessage***************"+msg.obj);
        switch (msg.what) {
        case MESSAGE_STATE_CHANGE:
            if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
            switch (msg.arg1) {
            case BluetoothChatService.STATE_CONNECTED:
                mTitle.setText(R.string.title_connected_to);
                mTitle.append(mConnectedDeviceName);
                mConversationArrayAdapter.clear();
                break;
            case BluetoothChatService.STATE_CONNECTING:
                mTitle.setText(R.string.title_connecting);
                break;
            case BluetoothChatService.STATE_LISTEN:
            case BluetoothChatService.STATE_NONE:
                mTitle.setText(R.string.title_not_connected);
                break;
            }
            break;
        case MESSAGE_WRITE:
            byte[] writeBuf = (byte[]) msg.obj;
            // construct a string from the buffer
            String writeMessage = new String(writeBuf);
            mConversationArrayAdapter.add("Me:  " + writeMessage);
            break;
        case MESSAGE_READ:
            System.out.println("***************msg.obj***************"+msg.obj);
            byte[] readBuf = (byte[]) msg.obj;

            System.out.println("***************readBuf***************"+readBuf.length);
            Bitmap bmp=BitmapFactory.decodeByteArray(readBuf,0,readBuf.length);
            System.out.println("***************bmp***************"+bmp);

            //convert it back to an image
            ByteArrayInputStream imageStream = new ByteArrayInputStream(readBuf);
            Bitmap theImage = BitmapFactory.decodeStream(imageStream);
            System.out.println("***************theImage***************"+theImage);
            try
            {
            String filepath=Environment.getExternalStorageDirectory().getAbsolutePath();
            File file = new File(filepath, "barcode.PNG");
            FileOutputStream fos = new FileOutputStream(file); 
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            theImage.compress(CompressFormat.JPEG, 100, fos);
            bos.flush();
            bos.close();
            }
            catch(Exception e)
            {
                System.out.println("***************Read***************"+e);
            }

案件MESSAGE_READ:一次又一次地打电话。我通过蓝牙发送图像。在发送方并在接收方获得1024字节的块..

任何帮助都将不胜感激。

由于

1 个答案:

答案 0 :(得分:3)

如果您事先知道整个尺寸,请将它们写入ByteArrayOutputStream,预先分配。完成后调用toArray()以获得结果。