Android.mk
- LOCAL_PATH := $(call my-dir)
-
- include $(CLEAR_VARS)
-
- LOCAL_MODULE := serial_port
- LOCAL_SRC_FILES := SerialPort.c
-
- LOCAL_LDLIBS := -llog
- include $(BUILD_SHARED_LIBRARY)
然后,直接在目录下ndk-build一下,便可得到我们需要的lib库文件。看看怎么调用吧,首先在SerialPort.
Java中实现打开和关闭串口,引用了lib 库
- package com.huangcheng.serial;
-
- import java.io.File;
- import java.io.FileDescriptor;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
-
- import android.util.Log;
-
- 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 {
-
- 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) {
- 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);
- }
-
-
- public InputStream getInputStream() {
- return mFileInputStream;
- }
-
- public OutputStream getOutputStream() {
- return mFileOutputStream;
- }
-
-
- private native static FileDescriptor open(String path, int baudrate, int flags);
- public native void close();
- static {
- System.loadLibrary("serial_port");
- }
- }
然后他做了一个很聪明的控制串口打开和关闭的类Application.java,继承自android.app.Application 这样,他便可以在所有的Activity类中调用实现串口打开和关闭。
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- package com.huangcheng.serial;
-
- import java.io.File;
- import java.io.IOException;
- import java.security.InvalidParameterException;
-
- public class Application extends android.app.Application {
-
- private SerialPort mSerialPort = null;
-
- public SerialPort getSerialPort() throws SecurityException, IOException, InvalidParameterException {
- if (mSerialPort == null) {
-
- mSerialPort = new SerialPort(new File("/dev/ttyUSB0"),19200, 0);
- }
- return mSerialPort;
- }
-
- public void closeSerialPort() {
- if (mSerialPort != null) {
- mSerialPort.close();
- mSerialPort = null;
- }
- }
- }
