Android 串口读取设备相关知识。。总结比较乱,部分转载(未完)

首先要提到JNI

Java Native Interface (JNI)标准是java平台的一部分,它允许Java代码和其他语言写的代码进行交互。JNI 是本地编程接口,它使得在 Java 虚拟机 (VM) 内部运行的 Java 代码能够与用其它编程语言(如 C、C++ 和汇编语言)编写的应用程序和库进行交互操作。

此外,在执行Java类的过程中,如果Java类需要与C组件沟通时,VM就会去载入C组件,然后让Java的函数顺利地调用到C组件的函数。此时,VM扮演着桥梁的角色,让Java与C组件能通过标准的JNI介面而相互沟通。

    应用层的Java类是在虚拟机(VM: Vitual Machine)上执行的,而C件不是在VM上执行,那么Java程式又如何要求VM去载入(Load)所指定的C组件呢? 可使用下述指令:

     System.loadLibrary(*.so的档案名);

 例如,Android框架里所提供的MediaPlayer.java类,含指令:

复制代码
  
  
public class MediaPlayer{ static { System.loadLibrary( " media_jni " ); } }

     这要求VM去载入Android的/system/lib/libmedia_jni.so档案。载入*.so之后,Java类与*.so档案就汇合起来,一起执行了。

2.如何撰写*.so的入口函数

    ---- JNI_OnLoad()与JNI_OnUnload()函数的用途

 当Android的VM(Virtual Machine)执行到System.loadLibrary()函数时,首先会去执行C组件里的JNI_OnLoad()函数。它的用途有二:

(1)告诉VM此C组件使用那一个JNI版本。如果你的*.so档没有提供JNI_OnLoad()函数,VM会默认该*.so档是使用最老的JNI 1.1版本。由于新版的JNI做了许多扩充,如果需要使用JNI的新版功能,例如JNI 1.4的java.nio.ByteBuffer,就必须藉由JNI_OnLoad()函数来告知VM。

(2)由于VM执行到System.loadLibrary()函数时,就会立即先呼叫JNI_OnLoad(),所以C组件的开发者可以藉由JNI_OnLoad()来进行C组件内的初期值之设定(Initialization) 。

例如,在Android的/system/lib/libmedia_jni.so档案里,就提供了JNI_OnLoad()函数,其程式码片段为:

复制代码
  
  
// #define LOG_NDEBUG 0 #define LOG_TAG " MediaPlayer-JNI " jint JNI_OnLoad(JavaVM * vm, void * reserved) { JNIEnv * env = NULL; jint result = - 1 ; if (vm -> GetEnv(( void ** ) & env, JNI_VERSION_1_4) != JNI_OK) { LOGE( " ERROR: GetEnv failed\n " ); goto bail; } assert (env != NULL); if (register_android_media_MediaPlayer(env) < 0 ) { LOGE( " ERROR: MediaPlayer native registration failed\n " ); goto bail; } if (register_android_media_MediaRecorder(env) < 0 ) { LOGE( " ERROR: MediaRecorder native registration failed\n " ); goto bail; } if (register_android_media_MediaScanner(env) < 0 ) { LOGE( " ERROR: MediaScanner native registration failed\n " ); goto bail; } if (register_android_media_MediaMetadataRetriever(env) < 0 ) { LOGE( " ERROR: MediaMetadataRetriever native registration failed\n " ); goto bail; } /* success -- return valid version number */ result = JNI_VERSION_1_4; bail: return result; }
复制代码

 此函数回传JNI_VERSION_1_4值给VM,于是VM知道了其所使用的JNI版本了。此外,它也做了一些初期的动作(可呼叫任何本地函数),例如指令:

复制代码
  
  
if (register_android_media_MediaPlayer(env) < 0 ) { LOGE( " ERROR: MediaPlayer native registration failed\n " ); goto bail; }
复制代码

就将此组件提供的各个本地函数(Native Function)登记到VM里,以便能加快后续呼叫本地函数的效率。

JNI_OnUnload()函数与JNI_OnLoad()相对应的。在载入C组件时会立即呼叫JNI_OnLoad()来进行组件内的初期动作;而当VM释放该C组件时,则会呼叫JNI_OnUnload()函数来进行善后清除动作。当VM呼叫JNI_OnLoad()或JNI_Unload()函数时,都会将VM的指针(Pointer)传递给它们,其参数如下:

jint JNI_OnLoad(JavaVM* vm, void* reserved) {     }

jint JNI_OnUnload(JavaVM* vm, void* reserved){     }

在JNI_OnLoad()函数里,就透过VM之指标而取得JNIEnv之指标值,并存入env指标变数里,如下述指令:

复制代码
  
  
jint JNI_OnLoad(JavaVM * vm, void * reserved){ JNIEnv * env = NULL; jint result = - 1 ; if (vm -> GetEnv(( void ** ) & env, JNI_VERSION_1_4) != JNI_OK) { LOGE( " ERROR: GetEnv failed\n " ); goto bail; } }
复制代码

由于VM通常是多执行绪(Multi-threading)的执行环境。每一个执行绪在呼叫JNI_OnLoad()时,所传递进来的JNIEnv指标值都是不同的。为了配合这种多执行绪的环境,C组件开发者在撰写本地函数时,可藉由JNIEnv指标值之不同而避免执行绪的资料冲突问题,才能确保所写的本地函数能安全地在Android的多执行绪VM里安全地执行。基于这个理由,当在呼叫C组件的函数时,都会将JNIEnv指标值传递给它,如下:

复制代码
  
  
jint JNI_OnLoad(JavaVM * vm, void * reserved) { JNIEnv * env = NULL; if (register_android_media_MediaPlayer(env) < 0 ) { } }
复制代码

这JNI_OnLoad()呼叫register_android_media_MediaPlayer(env)函数时,就将env指标值传递过去。如此,在register_android_media_MediaPlayer()函数就能藉由该指标值而区别不同的执行绪,以便化解资料冲突的问题。

 例如,在register_android_media_MediaPlayer()函数里,可撰写下述指令:

       if ((*env)->MonitorEnter(env, obj) != JNI_OK) {

       }

查看是否已经有其他执行绪进入此物件,如果没有,此执行绪就进入该物件里执行了。还有,也可撰写下述指令:

       if ((*env)->MonitorExit(env, obj) != JNI_OK) {

        }

查看是否此执行绪正在此物件内执行,如果是,此执行绪就会立即离开。

3.registerNativeMethods()函数的用途

应用层级的Java类别透过VM而呼叫到本地函数。一般是仰赖VM去寻找*.so里的本地函数。如果需要连续呼叫很多次,每次都需要寻找一遍,会多花许多时间。此时,组件开发者可以自行将本地函数向VM进行登记。例如,在Android的/system/lib/libmedia_jni.so档案里的代码段如下:

复制代码
  
  
// #define LOG_NDEBUG 0 #define LOG_TAG " MediaPlayer-JNI " static JNINativeMethod gMethods[] = { { " setDataSource " , " (Ljava/lang/String;)V " , ( void * )android_media_MediaPlayer_setDataSource}, { " setDataSource " , " (Ljava/io/FileDescriptor;JJ)V " , ( void * )android_media_MediaPlayer_setDataSourceFD}, { " prepare " , " ()V " , ( void * )android_media_MediaPlayer_prepare}, { " prepareAsync " , " ()V " , ( void * )android_media_MediaPlayer_prepareAsync}, { " _start " , " ()V " , ( void * )android_media_MediaPlayer_start}, { " _stop " , " ()V " , ( void * )android_media_MediaPlayer_stop}, { " getVideoWidth " , " ()I " , ( void * )android_media_MediaPlayer_getVideoWidth}, { " getVideoHeight " , " ()I " , ( void * )android_media_MediaPlayer_getVideoHeight}, { " seekTo " , " (I)V " , ( void * )android_media_MediaPlayer_seekTo}, { " _pause " , " ()V " , ( void * )android_media_MediaPlayer_pause}, { " isPlaying " , " ()Z " , ( void * )android_media_MediaPlayer_isPlaying}, { " getCurrentPosition " , " ()I " , ( void * )android_media_MediaPlayer_getCurrentPosition}, { " getDuration " , " ()I " , ( void * )android_media_MediaPlayer_getDuration}, { " _release " , " ()V " , ( void * )android_media_MediaPlayer_release}, { " _reset " , " ()V " , ( void * )android_media_MediaPlayer_reset}, { " setAudioStreamType " , " (I)V " , ( void * )android_media_MediaPlayer_setAudioStreamType}, { " setLooping " , " (Z)V " , ( void * )android_media_MediaPlayer_setLooping}, { " setVolume " , " (FF)V " , ( void * )android_media_MediaPlayer_setVolume}, { " getFrameAt " , " (I)Landroid/graphics/Bitmap; " , ( void * )android_media_MediaPlayer_getFrameAt}, { " native_setup " , " (Ljava/lang/Object;)V " , ( void * )android_media_MediaPlayer_native_setup}, { " native_finalize " , " ()V " , ( void * )android_media_MediaPlayer_native_finalize}, }; static int register_android_media_MediaPlayer(JNIEnv * env){ return AndroidRuntime::registerNativeMethods(env, " android/media/MediaPlayer " , gMethods, NELEM(gMethods)); } jint JNI_OnLoad(JavaVM * vm, void * reserved){ if (register_android_media_MediaPlayer(env) < 0 ) { LOGE( " ERROR: MediaPlayer native registration failed\n " ); goto bail; } }
复制代码

当VM载入libmedia_jni.so档案时,就呼叫JNI_OnLoad()函数。接着,JNI_OnLoad()呼叫register_android_media_MediaPlayer()函数。此时,就呼叫到AndroidRuntime::registerNativeMethods()函数,向VM(即AndroidRuntime)登记gMethods[]表格所含的本地函数了。简而言之,registerNativeMethods()函数的用途有二:

(1)更有效率去找到函数。

(2)可在执行期间进行抽换。由于gMethods[]是一个<名称,函数指针>对照表,在程序执行时,可多次呼叫registerNativeMethods()函数来更换本地函数之指针,而达到弹性抽换本地函数之目的。

4.Andoird 中使用了一种不同传统Java JNI的方式来定义其native的函数。其中很重要的区别是Andorid使用了一种Java 和 C 函数的映射表数组,并在其中描述了函数的参数和返回值。这个数组的类型是JNINativeMethod,定义如下:

复制代码
  
  
typedef struct { const char * name; /* Java中函数的名字 */ const char * signature; /* 描述了函数的参数和返回值 */ void * fnPtr; /* 函数指针,指向C函数 */ } JNINativeMethod;
复制代码

其中比较难以理解的是第二个参数,例如

"()V"

"(II)V"

"(Ljava/lang/String;Ljava/lang/String;)V"

实际上这些字符是与函数的参数类型一一对应的。

"()" 中的字符表示参数,后面的则代表返回值。例如"()V" 就表示void Func();

"(II)V" 表示 void Func(int, int);

具体的每一个字符的对应关系如下

字符   Java类型     C类型

V      void         void

Z      jboolean     boolean

I       jint         int

J       jlong        long

D      jdouble       double

F      jfloat            float

B      jbyte            byte

C      jchar           char

S      jshort          short

数组则以"["开始,用两个字符表示

[I     jintArray       int[]

[F     jfloatArray     float[]

[B     jbyteArray     byte[]

[C    jcharArray      char[]

[S    jshortArray      short[]

[D    jdoubleArray    double[]

[J     jlongArray      long[]

[Z    jbooleanArray    boolean[]

上面的都是基本类型。如果Java函数的参数是class,则以"L"开头,以";"结尾,中间是用"/" 隔开的包及类名。而其对应的C函数名的参数则为jobject. 一个例外是String类,其对应的类为jstring

Ljava/lang/String; String jstring

Ljava/net/Socket; Socket jobject

如果JAVA函数位于一个嵌入类,则用$作为类名间的分隔符。

例如 "(Ljava/lang/String;Landroid/os/FileUtils$FileStatus;)Z"

Android JNI编程实践

一、直接使用java本身jni接口(windows/ubuntu)

1.在Eclipsh中新建一个android应用程序。两个类:一个继承于Activity,UI显示用。另一个包含native方法。编译生成所有类。

jnitest.java文件:

复制代码
  
  
package com.hello.jnitest; import android.app.Activity; import android.os.Bundle; public class jnitest extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); Nadd cal = new Nadd(); setTitle( " The Native Add Result is " + String.valueOf(cal.nadd( 10 , 19 ))); } } Nadd.java文件: package com.hello.jnitest; public class Nadd { static { System.loadLibrary( " Nadd " ); } public native int nadd( int a, int b); }
复制代码

以上在windows中完成。

2.使用javah命令生成C/C++的.h文件。注意类要包含包名,路径文件夹下要包含所有包中的类,否则会报找不到类的错误。classpath参数指定到包名前一级文件夹,文件夹层次结构要符合java类的组织层次结构。

javah -classpath ../jnitest/bin com.hello.jnitest.Nadd

com_hello_jnitest_Nadd .h文件:

复制代码
  
  
/* DO NOT EDIT THIS FILE - it is machine generated */ #include < jni.h > /* Header for class com_hello_jnitest_Nadd */ #ifndef _Included_com_hello_jnitest_Nadd #define _Included_com_hello_jnitest_Nadd #ifdef __cplusplus extern " C " { #endif /* * Class: com_hello_jnitest_Nadd * Method: nadd * Signature: (II)I */ JNIEXPORT jint JNICALL Java_com_hello_jnitest_Nadd_nadd (JNIEnv * , jobject, jint, jint); #ifdef __cplusplus } #endif #endif
复制代码

3.编辑.c文件实现native方法。

com_hello_jnitest_Nadd.c文件:

复制代码
  
  
#include < stdlib.h > #include " com_hello_jnitest_Nadd.h " JNIEXPORT jint JNICALL Java_com_hello_jnitest_Nadd_nadd(JNIEnv * env, jobject c, jint a, jint b) { return (a + b); }
复制代码

4.编译.c文件生存动态库。

arm-none-linux-gnueabi-gcc -I/home/a/work/android/jdk1.6.0_17/include -I/home/a/work/android/jdk1.6.0_17/include/linux -fpic -c com_hello_jnitest_Nadd.c

arm-none-linux-gnueabi-ld -T/home/a/CodeSourcery/Sourcery_G++_Lite/arm-none-linux-gnueabi/lib/ldscripts/armelf_linux_eabi.xsc -share -o libNadd.so com_hello_jnitest_Nadd.o

得到libNadd.so文件。

以上在ubuntu中完成。

5.将相应的动态库文件push到avd的system/lib中:adb push libNadd.so /system/lib。若提示Read-only file system错误,运行adb remount命令,即可。

Adb push libNadd.so /system/lib

6.在eclipsh中运行原应用程序即可。

以上在windows中完成。

对于一中生成的so文件也可采用二中的方法编译进apk包中。只需在工程文件夹中建libs\armeabi文件夹(其他文件夹名无效,只建立libs文件夹也无效),然后将so文件拷入,编译工程即可。

二.使用NDK生成本地方法(ubuntu and windows)

1.安装NDK:解压,然后进入NDK解压后的目录,运行build/host-setup.sh(需要Make 3.81和awk)。若有错,修改host-setup.sh文件:将#!/bin/sh修改为#!/bin/bash,再次运行即可。

2.在apps文件夹下建立自己的工程文件夹,然后在该文件夹下建一文件Application.mk和项project文件夹。

Application.mk文件:

APP_PROJECT_PATH := $(call my-dir)/project

APP_MODULES      := myjni

3.在project文件夹下建一jni文件夹,然后新建Android.mk和myjni.c。这里不需要用javah生成相应的.h文件,但函数名要包含相应的完整的包、类名。

4.编辑相应文件内容。

Android.mk文件:

复制代码
  
  
# Copyright (C) 2009 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the " License " ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http: // www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an " AS IS " BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # LOCAL_PATH : = $(call my - dir) include $(CLEAR_VARS) LOCAL_MODULE : = myjni LOCAL_SRC_FILES : = myjni.c include $(BUILD_SHARED_LIBRARY)
复制代码

myjni.c文件:

复制代码
  
  
#include < string.h > #include < jni.h > jstring Java_com_hello_NdkTest_NdkTest_stringFromJNI( JNIEnv * env, jobject thiz ) { return ( * env) -> NewStringUTF(env, " Hello from My-JNI ! " ); }
复制代码

myjni文件组织:

a@ubuntu:~/work/android/ndk-1.6_r1/apps$ tree myjni

myjni

|-- Application.mk

`-- project

    |-- jni

    |   |-- Android.mk

    |   `-- myjni.c

    `-- libs

        `-- armeabi

            `-- libmyjni.so

4 directories, 4 files

5.编译:make APP=myjni.

以上内容在ubuntu完成。以下内容在windows中完成。当然也可以在ubuntu中完成。

6.在eclipsh中创建android application。将myjni中自动生成的libs文件夹拷贝到当前工程文件夹中,编译运行即可。

NdkTest.java文件:

复制代码
  
  
package com.hello.NdkTest; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class NdkTest extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); TextView tv = new TextView( this ); tv.setText( stringFromJNI() ); setContentView(tv); } public native String stringFromJNI(); static { System.loadLibrary( " myjni " ); } }
复制代码

对于二中生成的so文件也可采用一中的方法push到avd中运行。

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/linweig/archive/2010/03/26/5417319.aspx

在Android串口通信:基本知识梳理(http://gqdy365.iteye.com/admin/blogs/2188846)的基础上,我结合我项目中使用串口的实例,进行总结; 

Android使用jni直接进行串口设备的读写网上已经有开源项目了,本文是基于网上的开源项目在实际项目中的使用做的调整和优化; 
Google串口开源项目见:https://code.google.com/p/android-serialport-api/ 

下面是我项目中的相关代码及介绍: 

1、SerialPort.cpp 
Java代码   收藏代码
  1. /* 
  2.  * Copyright 2009 Cedric Priscal 
  3.  * 
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  * 
  8.  * http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  */  
  16. #include <stdlib.h>  
  17. #include <stdio.h>  
  18. #include <jni.h>  
  19. #include <assert.h>  
  20.   
  21. #include <termios.h>  
  22. #include <unistd.h>  
  23. #include <sys/types.h>  
  24. #include <sys/stat.h>  
  25. #include <fcntl.h>  
  26. #include <string.h>  
  27. #include <jni.h>  
  28.   
  29. #include "android/log.h"  
  30. static const char *TAG = "serial_port";  
  31. #define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO,  TAG, fmt, ##args)  
  32. #define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, TAG, fmt, ##args)  
  33. #define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, TAG, fmt, ##args)  
  34.   
  35. static speed_t getBaudrate(jint baudrate) {  
  36.     switch (baudrate) {  
  37.     case 0:  
  38.         return B0;  
  39.     case 50:  
  40.         return B50;  
  41.     case 75:  
  42.         return B75;  
  43.     case 110:  
  44.         return B110;  
  45.     case 134:  
  46.         return B134;  
  47.     case 150:  
  48.         return B150;  
  49.     case 200:  
  50.         return B200;  
  51.     case 300:  
  52.         return B300;  
  53.     case 600:  
  54.         return B600;  
  55.     case 1200:  
  56.         return B1200;  
  57.     case 1800:  
  58.         return B1800;  
  59.     case 2400:  
  60.         return B2400;  
  61.     case 4800:  
  62.         return B4800;  
  63.     case 9600:  
  64.         return B9600;  
  65.     case 19200:  
  66.         return B19200;  
  67.     case 38400:  
  68.         return B38400;  
  69.     case 57600:  
  70.         return B57600;  
  71.     case 115200:  
  72.         return B115200;  
  73.     case 230400:  
  74.         return B230400;  
  75.     case 460800:  
  76.         return B460800;  
  77.     case 500000:  
  78.         return B500000;  
  79.     case 576000:  
  80.         return B576000;  
  81.     case 921600:  
  82.         return B921600;  
  83.     case 1000000:  
  84.         return B1000000;  
  85.     case 1152000:  
  86.         return B1152000;  
  87.     case 1500000:  
  88.         return B1500000;  
  89.     case 2000000:  
  90.         return B2000000;  
  91.     case 2500000:  
  92.         return B2500000;  
  93.     case 3000000:  
  94.         return B3000000;  
  95.     case 3500000:  
  96.         return B3500000;  
  97.     case 4000000:  
  98.         return B4000000;  
  99.     default:  
  100.         return -1;  
  101.     }  
  102. }  
  103.   
  104. /* 
  105.  * Class:     cedric_serial_SerialPort 
  106.  * Method:    open 
  107.  * Signature: (Ljava/lang/String;)V 
  108.  */  
  109. JNIEXPORT jobject JNICALL native_open(JNIEnv *env, jobject thiz, jstring path,jint baudrate) {  
  110.     int fd;  
  111.     speed_t speed;  
  112.     jobject mFileDescriptor;  
  113.   
  114.     LOGD("init native Check arguments");  
  115.     /* Check arguments */  
  116.     {  
  117.         speed = getBaudrate(baudrate);  
  118.         if (speed == -1) {  
  119.             /* TODO: throw an exception */  
  120.             LOGE("Invalid baudrate");  
  121.             return NULL;  
  122.         }  
  123.     }  
  124.   
  125.     LOGD("init native Opening device!");  
  126.     /* Opening device */  
  127.     {  
  128.         jboolean iscopy;  
  129.         const char *path_utf = env->GetStringUTFChars(path, &iscopy);  
  130.         LOGD("Opening serial port %s", path_utf);  
  131. //      fd = open(path_utf, O_RDWR | O_DIRECT | O_SYNC);  
  132.         fd = open(path_utf, O_RDWR | O_NOCTTY | O_NONBLOCK | O_NDELAY);  
  133.         LOGD("open() fd = %d", fd);  
  134.         env->ReleaseStringUTFChars(path, path_utf);  
  135.         if (fd == -1) {  
  136.             /* Throw an exception */  
  137.             LOGE("Cannot open port %d",baudrate);  
  138.             /* TODO: throw an exception */  
  139.             return NULL;  
  140.         }  
  141.     }  
  142.   
  143.     LOGD("init native Configure device!");  
  144.     /* Configure device */  
  145.     {  
  146.         struct termios cfg;  
  147.         if (tcgetattr(fd, &cfg)) {  
  148.             LOGE("Configure device tcgetattr() failed 1");  
  149.             close(fd);  
  150.             return NULL;  
  151.         }  
  152.   
  153.         cfmakeraw(&cfg);  
  154.         cfsetispeed(&cfg, speed);  
  155.         cfsetospeed(&cfg, speed);  
  156.   
  157.         if (tcsetattr(fd, TCSANOW, &cfg)) {  
  158.             LOGE("Configure device tcsetattr() failed 2");  
  159.             close(fd);  
  160.             /* TODO: throw an exception */  
  161.             return NULL;  
  162.         }  
  163.     }  
  164.   
  165.     /* Create a corresponding file descriptor */  
  166.     {  
  167.         jclass cFileDescriptor = env->FindClass("java/io/FileDescriptor");  
  168.         jmethodID iFileDescriptor = env->GetMethodID(cFileDescriptor,"<init>""()V");  
  169.         jfieldID descriptorID = env->GetFieldID(cFileDescriptor,"descriptor""I");  
  170.         mFileDescriptor = env->NewObject(cFileDescriptor,iFileDescriptor);  
  171.         env->SetIntField(mFileDescriptor, descriptorID, (jint) fd);  
  172.     }  
  173.   
  174.     return mFileDescriptor;  
  175. }  
  176.   
  177. /* 
  178.  * Class:     cedric_serial_SerialPort 
  179.  * Method:    close 
  180.  * Signature: ()V 
  181.  */  
  182. JNIEXPORT jint JNICALL native_close(JNIEnv * env, jobject thiz)  
  183. {  
  184.     jclass SerialPortClass = env->GetObjectClass(thiz);  
  185.     jclass FileDescriptorClass = env->FindClass("java/io/FileDescriptor");  
  186.   
  187.     jfieldID mFdID = env->GetFieldID(SerialPortClass, "mFd""Ljava/io/FileDescriptor;");  
  188.     jfieldID descriptorID = env->GetFieldID(FileDescriptorClass, "descriptor""I");  
  189.   
  190.     jobject mFd = env->GetObjectField(thiz, mFdID);  
  191.     jint descriptor = env->GetIntField(mFd, descriptorID);  
  192.   
  193.     LOGD("close(fd = %d)", descriptor);  
  194.     close(descriptor);  
  195.     return 1;  
  196. }  
  197.   
  198. static JNINativeMethod gMethods[] = {  
  199.         { "open""(Ljava/lang/String;I)Ljava/io/FileDescriptor;",(void*) native_open },  
  200.         { "close""()I",(void*) native_close },  
  201. };  
  202.   
  203. /* 
  204.  * 为某一个类注册本地方法 
  205.  */  
  206. static int registerNativeMethods(JNIEnv* env, const char* className,  
  207.         JNINativeMethod* gMethods, int numMethods) {  
  208.     jclass clazz;  
  209.     clazz = env->FindClass(className);  
  210.     if (clazz == NULL) {  
  211.         return JNI_FALSE;  
  212.     }  
  213.     if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) {  
  214.         return JNI_FALSE;  
  215.     }  
  216.   
  217.     return JNI_TRUE;  
  218. }  
  219.   
  220. /* 
  221.  * 为所有类注册本地方法 
  222.  */  
  223. static int registerNatives(JNIEnv* env) {  
  224.     const char* kClassName = "com/jerome/serialport/SerialPort"//指定要注册的类  
  225.     return registerNativeMethods(env, kClassName, gMethods,  
  226.             sizeof(gMethods) / sizeof(gMethods[0]));  
  227. }  
  228.   
  229. /* 
  230.  * System.loadLibrary("lib")时调用 
  231.  * 如果成功返回JNI版本, 失败返回-1 
  232.  */  
  233. JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {  
  234.     JNIEnv* env = NULL;  
  235.     jint result = -1;  
  236.   
  237.     if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {  
  238.         return -1;  
  239.     }  
  240.     assert(env != NULL);  
  241.   
  242.     if (!registerNatives(env)) { //注册  
  243.         return -1;  
  244.     }  
  245.     //成功  
  246.     result = JNI_VERSION_1_4;  
  247.   
  248.     return result;  
  249. }  


在编译时注意修改const char* kClassName = "com/jerome/serialport/SerialPort";为你Java层与jni对应得包名; 

2、Android.mk 
Java代码   收藏代码
  1. LOCAL_PATH := $(call my-dir)  
  2.   
  3. include $(CLEAR_VARS)  
  4.   
  5. TARGET_PLATFORM := android-3  
  6. LOCAL_MODULE    := serial_port  
  7. LOCAL_SRC_FILES := SerialPort.cpp  
  8. LOCAL_LDLIBS    := -llog  
  9.   
  10. include $(BUILD_SHARED_LIBRARY)  


如果要修改生成so文件的名称,请修改LOCAL_MODULE    := serial_port 

3、SerialPort.java 
Java代码   收藏代码
  1. package com.jerome.serialport;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileDescriptor;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStream;  
  9. import java.io.OutputStream;  
  10.   
  11. public class SerialPort {  
  12.   
  13.     private static final String TAG = "SerialPort";  
  14.     /* 
  15.      * Do not remove or rename the field mFd: it is used by native method close(); 
  16.      */  
  17.     private FileDescriptor mFd;  
  18.     private FileInputStream mFileInputStream;  
  19.     private FileOutputStream mFileOutputStream;  
  20.   
  21.     public SerialPort(File device, int baudrate) throws SecurityException, IOException {  
  22.         mFd = open(device.getAbsolutePath(), baudrate);  
  23.         if (mFd == null) {  
  24.             throw new IOException();  
  25.         }  
  26.         mFileInputStream = new FileInputStream(mFd);  
  27.         mFileOutputStream = new FileOutputStream(mFd);  
  28.     }  
  29.   
  30.     public InputStream getInputStream() {  
  31.         return mFileInputStream;  
  32.     }  
  33.   
  34.     public OutputStream getOutputStream() {  
  35.         return mFileOutputStream;  
  36.     }  
  37.   
  38.     private native FileDescriptor open(String path, int baudrate);  
  39.     public native int close();  
  40.   
  41.     static {  
  42.         System.loadLibrary("serial_port");  
  43.     }  
  44. }  


4、SerialPortUtil.java 

Java代码   收藏代码
  1. package com.jerome.serialport;  
  2.   
  3. import java.io.BufferedWriter;  
  4. import java.io.File;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8. import java.io.OutputStreamWriter;  
  9. import java.io.PrintWriter;  
  10.   
  11. /** 
  12.  * 串口操作类 
  13.  *  
  14.  * @author Jerome 
  15.  *  
  16.  */  
  17. public class SerialPortUtil {  
  18.     private String TAG = SerialPortUtil.class.getSimpleName();  
  19.     private SerialPort mSerialPort;  
  20.     private OutputStream mOutputStream;  
  21.     private InputStream mInputStream;  
  22.     private ReadThread mReadThread;  
  23.     private String path = "/dev/ttyMT1";  
  24.     private int baudrate = 115200;  
  25.     private static SerialPortUtil portUtil;  
  26.     private OnDataReceiveListener onDataReceiveListener = null;  
  27.     private boolean isStop = false;  
  28.   
  29.     public interface OnDataReceiveListener {  
  30.         public void onDataReceive(byte[] buffer, int size);  
  31.     }  
  32.   
  33.     public void setOnDataReceiveListener(  
  34.             OnDataReceiveListener dataReceiveListener) {  
  35.         onDataReceiveListener = dataReceiveListener;  
  36.     }  
  37.       
  38.     public static SerialPortUtil getInstance() {  
  39.         if (null == portUtil) {  
  40.             portUtil = new SerialPortUtil();  
  41.             portUtil.onCreate();  
  42.         }  
  43.         return portUtil;  
  44.     }  
  45.   
  46.     /** 
  47.      * 初始化串口信息 
  48.      */  
  49.     public void onCreate() {  
  50.         try {  
  51.             mSerialPort = new SerialPort(new File(path), baudrate);  
  52.             mOutputStream = mSerialPort.getOutputStream();  
  53.             mInputStream = mSerialPort.getInputStream();  
  54.               
  55.             mReadThread = new ReadThread();  
  56.             isStop = false;  
  57.             mReadThread.start();  
  58.         } catch (Exception e) {  
  59.             e.printStackTrace();  
  60.         }  
  61.         initBle();  
  62.     }  
  63.   
  64.     /** 
  65.      * 发送指令到串口 
  66.      *  
  67.      * @param cmd 
  68.      * @return 
  69.      */  
  70.     public boolean sendCmds(String cmd) {  
  71.         boolean result = true;  
  72.         byte[] mBuffer = (cmd+"\r\n").getBytes();  
  73. //注意:我得项目中需要在每次发送后面加\r\n,大家根据项目项目做修改,也可以去掉,直接发送mBuffer  
  74.         try {  
  75.             if (mOutputStream != null) {  
  76.                 mOutputStream.write(mBuffer);  
  77.             } else {  
  78.                 result = false;  
  79.             }  
  80.         } catch (IOException e) {  
  81.             e.printStackTrace();  
  82.             result = false;  
  83.         }  
  84.         return result;  
  85.     }  
  86.   
  87.     public boolean sendBuffer(byte[] mBuffer) {  
  88.         boolean result = true;  
  89.         String tail = "\r\n";  
  90.         byte[] tailBuffer = tail.getBytes();  
  91.         byte[] mBufferTemp = new byte[mBuffer.length+tailBuffer.length];  
  92.         System.arraycopy(mBuffer, 0, mBufferTemp, 0, mBuffer.length);  
  93.         System.arraycopy(tailBuffer, 0, mBufferTemp, mBuffer.length, tailBuffer.length);  
  94. //注意:我得项目中需要在每次发送后面加\r\n,大家根据项目项目做修改,也可以去掉,直接发送mBuffer  
  95.         try {  
  96.             if (mOutputStream != null) {  
  97.                 mOutputStream.write(mBufferTemp);  
  98.             } else {  
  99.                 result = false;  
  100.             }  
  101.         } catch (IOException e) {  
  102.             e.printStackTrace();  
  103.             result = false;  
  104.         }  
  105.         return result;  
  106.     }  
  107.   
  108.     private class ReadThread extends Thread {  
  109.   
  110.         @Override  
  111.         public void run() {  
  112.             super.run();  
  113.             while (!isStop && !isInterrupted()) {  
  114.                 int size;  
  115.                 try {  
  116.                     if (mInputStream == null)  
  117.                         return;  
  118.                     byte[] buffer = new byte[512];  
  119.                     size = mInputStream.read(buffer);  
  120.                     if (size > 0) {  
  121.                         if(MyLog.isDyeLevel()){  
  122.                             MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "length is:"+size+",data is:"+new String(buffer, 0, size));  
  123.                         }  
  124.                         if (null != onDataReceiveListener) {  
  125.                             onDataReceiveListener.onDataReceive(buffer, size);  
  126.                         }  
  127.                     }  
  128.                     Thread.sleep(10);  
  129.                 } catch (Exception e) {  
  130.                     e.printStackTrace();  
  131.                     return;  
  132.                 }  
  133.             }  
  134.         }  
  135.     }  
  136.   
  137.     /** 
  138.      * 关闭串口 
  139.      */  
  140.     public void closeSerialPort() {  
  141.         sendShellCommond1();  
  142.         isStop = true;  
  143.         if (mReadThread != null) {  
  144.             mReadThread.interrupt();  
  145.         }  
  146.         if (mSerialPort != null) {  
  147.             mSerialPort.close();  
  148.         }  
  149.     }  
  150.       
  151. }  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值