0

我正在开发一个蓝牙应用程序,我在其中创建了 Android 设备和硬件设备之间的连接。

我成功地从硬件设备发送和接受文本数据。

我在从硬件设备到 Android 设备的图像传输中遇到问题。

我正在使用以下代码从 BYTE ARRAY 创建位图并将其保存到 SDCard:

  public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
        if (D) Log.d(TAG, "connected");

        // Cancel the thread that completed the connection
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }

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

        //CREATE IMAGE FILE
        File empowered=new File(Environment.getExternalStorageDirectory(), "ImageFile.jpeg");

        if (empowered.exists()) {
            empowered.delete();
        }

        try {
            fos = new FileOutputStream(empowered.getPath());
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        try {

            //fos.write(buffer);
            bitmap = BitmapFactory.decodeByteArray(buffer , 0, buffer.length);

            bitmap.compress(CompressFormat.JPEG, 100, fos);


        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }


        setState(STATE_CONNECTED);
    }

接收代码:

public void run() {
        Log.i(TAG, "BEGIN mConnectedThread");

        // Keep listening to the InputStream while connected
        //while (true) {

        try {
            // Read from the InputStream
            bytes = mmInStream.read(buffer);
            if (bytes != -1) {
                //ensure DATAMAXSIZE Byte is read.
                int byteNo2 = bytes;
                int bufferSize = 7340;
                while(byteNo2 != bufferSize){
                    bufferSize = bufferSize - byteNo2;
                    byteNo2 = mmInStream.read(buffer,bytes,bufferSize);
                    if(byteNo2 == -1){
                        break;
                    }
                    bytes = bytes+byteNo2;
                }
            }
        }

    } catch (IOException e) {
        Log.e(TAG, "disconnected", e);
        testModeOnScreen.sendMailTest("emailAddress","Received bytes"+e.toString(),"IOEXCEPTION");
        connectionLost();
        //break;
    }
}
4

0 回答 0