Android扫描购物的COM口打印记录

turboksAndroid87
    /**
     *  打印数据
     */
    public void print(MainBean.Data data) {
        isShowQR = false;
        payLine.setVisibility(View.GONE);
        successLine.setVisibility(View.VISIBLE);
        //打开串口
        String devicePath = "/dev/ttyS0"; // 设备路径
        int baudrate = Integer.parseInt("115200"); // 波特率
        // 创建 SerialPortService
        SerialPortService mSerialPortService = new SerialPortService(this, devicePath, baudrate);
        // 如果打开成功,则打印数据;否则提示失败
        if (mSerialPortService.isActive()) {
            byte[] printData = PrintUtils.generateBillData(data);
            mSerialPortService.write(printData);
            // 这里可以每次打印完成后,关闭串口,节省资源。不关闭也可以。看个人喜好
            mSerialPortService.closeSerial();
            mSerialPortService = null;
        } else {
            Toast.makeText(this, "打印机串口不能使用", Toast.LENGTH_SHORT).show();
            mSerialPortService.closeSerial();
            mSerialPortService = null;
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //订单号、走扫码购流程
                Intent intent = new Intent();
                intent.putExtra("code", "8888");
                setResult(RESULT_CODE, intent);
                cancelTimer();
            }
        },4000);
    }
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //刷新数据
            refreshData();
        }
    };




public class SerialPortService {
    private SerialPort mSerialPort;
    private InputStream mInputStream;
    private OutputStream mOutputStream;
    private ReadThread mReadThread;
    private boolean isActive;
   // 无需更新UI,所以不需要 Handler 参数
    public SerialPortService(Context context, String devicePath, int baudrate) {
       // mHandler = handler;
        try {
            // mSerialPort = new SerialPort(new File("/dev/ttyS1"), 9600, 0);
            mSerialPort = new SerialPort(context,new File(devicePath), baudrate, 0); // 创建 SerialPort
            // 获取输入输出流,这样就可以对串口进行数据的读写了
            mInputStream = mSerialPort.getInputStream();
            mOutputStream = mSerialPort.getOutputStream();
            mReadThread = new ReadThread();
            mReadThread.start();
            isActive = true;
        } catch (IOException e) {
            e.printStackTrace();
            isActive = false;
        }
    }
    public boolean isActive() {
        return isActive;
    }
    public void write(byte[] data) {
        try {
            mOutputStream.write(data);
            Log.w("TAG", "write data: " + new String(data));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void closeSerial() {
        isActive = false;
//        mHandler.removeCallbacksAndMessages(null);
//        mHandler = null;
        if (mReadThread != null) {
            mReadThread.interrupt();
            mReadThread = null;
        }
        if (mSerialPort != null) {
            mSerialPort.close();
            mSerialPort = null;
        }
        try {
            if (mInputStream != null) {
                mInputStream.close();
                mInputStream = null;
            }
            if (mOutputStream != null) {
                mOutputStream.close();
                mOutputStream = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 不需要读取数据
     */
    class ReadThread extends Thread {
        private StringBuilder sb = new StringBuilder();
        private byte[] buf = new byte[128];
        @Override
        public void run() {
//            while (isActive) {
//                try {
//                    int len = mInputStream.read(buf);
//                    //Log.i("TAG", "length is:" + len + ",data is:" + new String(buf, 0, len));
//                    if (len != -1 && mHandler != null) {
//
//                        sb.append(new String(buf, 0, len));
//                        Log.i("TAG", sb.toString());
//
//                        mHandler.obtainMessage(0, new String(buf, 0, len)).sendToTarget();
//                    }
//                    Thread.sleep(200);  // 间隔200毫秒
//                } catch (IOException e) {
//                    e.printStackTrace();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
        }
    }
}



public class SerialPort {
    private static final String TAG = "SerialPort";
    /*
     * Do not remove or rename the field mFd: it is used by native method close();
     */
    private FileDescriptor mFd;
    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;
    public SerialPort(Context context, File device, int baudrate, int flags) throws SecurityException, IOException {
        /* Check access permission */
        if (!device.canRead() || !device.canWrite()) {
            try {
                /* Missing read/write permission, trying to chmod the file */
                Process su;
                su = Runtime.getRuntime().exec("/system/bin/su");
                String cmd = "chmod 666 " + device.getAbsolutePath() + "\n"
                        + "exit\n";
                su.getOutputStream().write(cmd.getBytes());
                if ((su.waitFor() != 0) || !device.canRead()
                        || !device.canWrite()) {
                    throw new SecurityException();
                }
            } catch (Exception e) {
                Toast.makeText(context, "error"+e, Toast.LENGTH_SHORT).show();
                Log.d(TAG, "SerialPortError: "+e);
                e.printStackTrace();
                throw new SecurityException();
            }
        }
        mFd = open(device.getAbsolutePath(), baudrate, flags);
        if (mFd == null) {
            Log.e(TAG, "native open returns null");
            throw new IOException();
        }
        mFileInputStream = new FileInputStream(mFd);
        mFileOutputStream = new FileOutputStream(mFd);
    }
    // Getters and setters
    public InputStream getInputStream() {
        return mFileInputStream;
    }
    public OutputStream getOutputStream() {
        return mFileOutputStream;
    }
    // JNI
    private native static FileDescriptor open(String path, int baudrate, int flags);
    public native void close();
    static {
        System.loadLibrary("SerialPort");
    }
}


相关文章

okhttp的使用

okhttp的使用

首先在build.gradle中倒入第三方库:        //okhttp网络请求    &...