1. 程式人生 > >Android串列埠開發簡單教程

Android串列埠開發簡單教程

public class SerialPort {
    private static final String TAG = "SerialPort";
    private FileDescriptor mFd;
    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;
    public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException {
        //檢查訪問許可權,如果沒有讀寫許可權,進行檔案操作,修改檔案訪問許可權
        if (!device.canRead() || !device.canWrite()) {
            try {
                //通過掛在到linux的方式,修改檔案的操作許可權
                Process su = Runtime.getRuntime().exec("/system/xbin/su");
                String cmd = "chmod 777 " + device.getAbsolutePath() + "\n" + "exit\n";
                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.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(呼叫java本地介面,實現串列埠的開啟和關閉)
/**串列埠有五個重要的引數:串列埠裝置名,波特率,檢驗位,資料位,停止位
 其中檢驗位一般預設位NONE,資料位一般預設為8,停止位預設為1*/
    /**
     * @param path     串列埠裝置的據對路徑
     * @param baudrate 波特率
     * @param flags    校驗位
     */
    private native static FileDescriptor open(String path, int baudrate, int flags);
    public native void close();
    static {//載入jni下的C檔案庫
        System.loadLibrary("serial_port");
    }
}
2.初始化