Android - 蓝牙打印机未完成打印但抛出IOException:Socket Closed

时间:2013-08-30 04:32:54

标签: android sockets printing bluetooth ioexception

我有一个应用程序可以将数据(文本和图像)打印到热敏打印机。

我的问题是每当我打印冗长的数据时,打印输出都会被切断,并且我在我打印的try catch语句中抛出IOException: Socket Closed

以下是我打印数据的部分:

protected void simpleComm(Integer port){
    //InputStream tmpIn = null;
    byte[] buffer = new byte[3]; //{65,65,53,53,49,52,65,66,67,68};

    buffer[0] = (byte) 0x08;
    buffer[1] = (byte) 0x99;
    buffer[2] = (byte) 0x04;
    OutputStream tmpOut;// = null;    

    bluetoothAdapter.cancelDiscovery();

    Log.d(this.toString(), "Port = " + port);
    try {


        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
        Method m = blueToothDevice.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
        socket = (BluetoothSocket) m.invoke(blueToothDevice, port);

        //socket = mmDevice.createRfcommSocketToServiceRecord(uuid);

        // assert (socket != null) : "Socket is Null";
        socket.connect();

        try {
            Log.d(this.toString(),"************ CONNECTION SUCCEES! *************");
            try{
                //tmpIn=socket.getInputStream();
                tmpOut = socket.getOutputStream();

                //mmInStream = tmpIn;
                mmOutStream = tmpOut;

            }
            catch(Exception ex){
                Log.e(this.toString(), "Exception " + ex.getMessage());
            }

            //TODO print sequence starts here

            image = "logo";
            print_image(Environment.getExternalStorageDirectory().toString() + "/LOGO.png");

            byte[] arrayOfByte1 = { 27, 33, 0 };
            byte[] format = { 27, 33, 0 };

            mmOutStream.write((newline).getBytes("US-ASCII"));


            //bold
            format[2] = ((byte)(0x0 | arrayOfByte1[2]));  
            //width
            format[2] = ((byte)(0x12 | arrayOfByte1[2]));
            //height
            format[2] = ((byte)(0x8 | arrayOfByte1[2]));
            mmOutStream.write(format);


            for(int i = 0 ; i < orderListForPrinting.size(); i++ ){
                mmOutStream.write(((List.get(i)).getBytes("US-ASCII")));
            }


            //bold
            format[2] = ((byte)(0x8 | arrayOfByte1[2]));  
            //width
            format[2] = ((byte)(0x8 | arrayOfByte1[2]));
            //height
            format[2] = ((byte)(0x8 | arrayOfByte1[2]));
            mmOutStream.write(format);

            mmOutStream.write((newline).getBytes("US-ASCII"));


            printSignature();

            //bold
            format[2] = ((byte)(0x8 | arrayOfByte1[2]));  
            //width
            format[2] = ((byte)(0x8 | arrayOfByte1[2]));
            //height
            format[2] = ((byte)(0x8 | arrayOfByte1[2]));
            mmOutStream.write(format);

            mmOutStream.write(( name + "                  " + newline + newline).getBytes("US-ASCII"));                

        }
        finally{

            orderList = new ArrayList<TotalOrderClass>();
            orderListForPrinting = new ArrayList<String>();
            socket.close();
            mmOutStream.flush();
        }
    } 
    catch (IOException ex){
        Log.e(this.toString(), "IOException: " + ex.getMessage());
    } 
    catch (NoSuchMethodException ex){
        Log.e(this.toString(), "NoSuchMethodException: " + ex.getMessage());
    } 
    catch (IllegalAccessException ex){
        Log.e(this.toString(), "IllegalAccessException: " + ex.getMessage());
    } 
    catch (InvocationTargetException ex){
        Log.e(this.toString(),"InvocationTargetException: " + ex.getMessage());
    }

}

这是我的打印签名功能,类似于我用来打印徽标的功能。

private void printSignature() {
    //TODO print signature here
    convertBitmap(signature);
    try{
        mmOutStream.write(PrinterCommands.SET_LINE_SPACING_24);

        int offset = 0;
        while (offset < signature.getHeight()) {
            mmOutStream.write(PrinterCommands.SELECT_BIT_IMAGE_MODE_SIGNATURE);
            for (int x = 0; x < signature.getWidth(); ++x) {

                for (int k = 0; k < 3; ++k) {

                    byte slice = 0;
                    for (int b = 0; b < 8; ++b) {
                        int y = (((offset / 8) + k) * 8) + b;
                        int i = (y * signature.getWidth()) + x;
                        boolean v = false;
                        if (i < dots.length()) {
                            v = dots.get(i);
                        }
                        slice |= (byte) ((v ? 1 : 0) << (7 - b));
                    }
                    mmOutStream.write(slice);
                }
            }
            offset += 24;
            mmOutStream.write(PrinterCommands.FEED_LINE);
        }

        mmOutStream.write(PrinterCommands.SET_LINE_SPACING_30);
    }
    catch (IOException e) {
        Toast.makeText(getApplicationContext(), "Catch on to print signature stuff", Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }

}

ConvertBitmap函数:

public String convertBitmap(Bitmap inputBitmap) {

    int mWidth = inputBitmap.getWidth();
    int mHeight = inputBitmap.getHeight();

    convertArgbToGrayscale(inputBitmap, mWidth, mHeight);
    String mStatus = "ok";
    return mStatus;

}

convertArgbToGrayScale函数:

private void convertArgbToGrayscale(Bitmap bmpOriginal, int width,
        int height) {
    int pixel;
    int k = 0;
    int B = 0, G = 0, R = 0;
    dots = new BitSet();
    try {

        for (int x = 0; x < height; x++) {
            for (int y = 0; y < width; y++) {
                // get one pixel color
                pixel = bmpOriginal.getPixel(y, x);

                // retrieve color of all channels
                R = Color.red(pixel);
                G = Color.green(pixel);
                B = Color.blue(pixel);
                // take conversion up to one single value by calculating
                // pixel intensity.
                R = G = B = (int) (0.299 * R + 0.587 * G + 0.114 * B);
                // set bit into bitset, by calculating the pixel's luma
                if (R < 55) {                       
                    dots.set(k);//this is the bitset that i'm printing
                }
                k++;

            }


        }


    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), "Catch on to Grayscale stuff", Toast.LENGTH_LONG).show();
    }
}

我现在的问题是,在调用printSignature()函数后,打印机停止打印并关闭套接字,这就是我收到IOException:Socket Closed错误的原因。

我已经完成了几次这个函数,我不知道为什么套接字正在关闭,因为我只关闭了try-catch的finally子句中的套接字。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

如果您在Thread.sleep(2000)之前放置socket.close(),会有什么好处?

我在蓝牙SPP上工作,我遇到了同样的问题(数据传输结束前Socket关闭)。我认为socket.close()的广播比数据的传输更快,然后当发送关闭请求时,BT打印机不会分析所有数据

答案 1 :(得分:0)

我做的是,我在每Thread.sleep(x)之后放置一个.Write(),其中x是输出字符串中的字符数,可以在您的代码中有所不同,但是等待程序在关闭之前必须做的,与打印的字符(或行)的数量成正比。