引入库类

Android通用串口工具类_ide

工具类

public class SerialPort {

    private static final String TAG = "SerialPort";
    /**
     * 不要删除或重命名字段mFd:原生方法close()使用了该字段
     */
    private FileDescriptor mFd;
    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;
    /**
     * 有些设备su路径是/system/xbin/su
     */
    private static String mSuPath = "/system/xbin/su";

    static {
        System.loadLibrary("android_serial_port");
    }

    public static void setSuPath(String suPath) {
        if (TextUtils.isEmpty(suPath)) {
            return;
        }
        mSuPath = suPath;
    }

    public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException {
        /* 检查访问权限 */
        if (!device.canRead() || !device.canWrite()) {
            try {
                /* 没有读/写权限,尝试对文件进行提权 */
                Process su = Runtime.getRuntime().exec(mSuPath);
                String cmd = "chmod 666 " + device.getAbsolutePath() + "\n" + "exit\n";

                BufferedReader in = new BufferedReader(new InputStreamReader(su.getInputStream()));
                BufferedReader ie = new BufferedReader(new InputStreamReader(su.getErrorStream()));
                BufferedWriter w = new BufferedWriter(new OutputStreamWriter(su.getOutputStream()));
                w.write(cmd);
                w.flush();
                w.close();
                String infoLine = "";
                while ((infoLine = in.readLine()) != null) {
                    Log.d("cmd", "输出:" + infoLine);
                }
                while ((infoLine = ie.readLine()) != null) {
                    Log.d("cmd", "错误:" + infoLine);
                }
                in.close();
                ie.close();
//                su.getOutputStream().write(cmd.getBytes());
                if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) {
                    throw new SecurityException();
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new SecurityException();
            }
        }
        mFd = open(device.getAbsolutePath(), baudrate, flags);
        if (mFd == null) {
            Log.i(TAG, "open() return null");
            throw new IOException();
        }
        mFileInputStream = new FileInputStream(mFd);
        mFileOutputStream = new FileOutputStream(mFd);
    }

    /**
     * 打开串口
     *
     * @param path     设备路径
     * @param baudrate 波特率
     * @param flags
     * @return FileDescriptor
     */
    private native static FileDescriptor open(String path, int baudrate, int flags);

    /**
     * 关闭串口
     */
    public native void close();

    public InputStream getInputStream() {
        return mFileInputStream;
    }

    public OutputStream getOutputStream() {
        return mFileOutputStream;
    }
}

调用类:

public class IcCardRead {
    private static String TAG = "IcCardRead";
    private static IcCardRead instance;


    public interface IcReadListening{
        void onReadIc(String ic);
    }

    private IcReadListening listening;
    public void setListening(IcReadListening listening) {
        this.listening = listening;
    }


    public static IcCardRead getInstance() {
        if (instance == null) {
            instance = new IcCardRead();
        }
        return instance;
    }



    private ExecutorService executorService = Executors.newCachedThreadPool();
    private SerialPort serialPort;
    private String path = "/dev/ttyCOM1";
    private int baudRate = 9600;
    private volatile boolean reading;

    private IcCardRead() {
    }

    public synchronized void open(String path, int baudRate) {
        try {
            if(serialPort  != null){
                serialPort.close();
                serialPort = null;
            }

            serialPort = new SerialPort(new File(path), baudRate, 0);
            read();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public synchronized void close() {
        reading = false;
        if (serialPort != null) {
            serialPort.close();
            serialPort = null;
        }
    }

    private void read() {
        if (reading) {
            return;
        }
        reading = true;
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                byte[] buffer = new byte[1024];
                while (reading) {
                    try {
                        if (serialPort.getInputStream().available() > 0) {
                            Thread.sleep(50);
                            int size = serialPort.getInputStream().read(buffer);
                            if (size > 0) {
                                String s = new String(buffer, 0, size);
                                s = s.substring(1, s.length() - 1);
                                Log.i(TAG, s);
                                if(listening != null){
                                    listening.onReadIc(s);
                                }
                            }
                        }
                        else {
                            Thread.sleep(100);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}

使用方法以读卡器为例:

public class ICCardLoginActivity extends BaseCommonStatusBarActivity {

    private static String TAG = "ICCardEntryActivity";
    private IcCardRead read;
    private TextView tvCrad;
    private Button mBack;

    @Override
    public int getCenterViewLayoutRes() {
        return R.layout.activity_ic_card;
    }

    @Override
    public void initView() {
        super.initView();
        tvCrad = (TextView)findViewById(R.id.tv_card);
        mBack = (Button) findViewById(R.id.back);
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
       
        read = IcCardRead.getInstance();
        read.setListening(new IcCardRead.IcReadListening() {
            /**
             *
             * @param ic 读取到的IC卡号
             */
            @Override
            public void onReadIc(final String ic) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvCrad.setText(ic);
                        
                        finish();
                    }
                });
                Log.i(TAG, ic);
            }
        });
        try {
            read.open("/dev/ttyS0", 9600);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    protected void onDestroy() {
        read.close();
        super.onDestroy();
    }

}