編輯:關於 Android 程式設計
提到串口編程,就不得不提 JNI,以及 Java API 中的文件描述符類 FileDescriptor。本文參考開源專案 android-serialport-api,說明 JNI、FileDescriptor 與串口相關知識,並解析應用層的實作方式(不涉及驅動層)。
串口編程的基本觀念是:對串口進行一系列設定後打開它,這些操作可參考串口調試助手。在 Java 中若要讀寫串口,只需操作文件設備類 FileDescriptor,其餘都交給驅動完成。
1、如何把編譯好的 SO 檔打包進 APK?很簡單,在工程目錄下新建 libs/armeabi 文件夾,把 SO 檔 Copy 進去即可。
2、命名要注意:把 SO 檔命名為 libfilename.so(filename.so 是編譯後生成的檔名)。
3、MakeFile 的編寫可直接參考 package/apps 目錄下用到 JNI 的專案寫法。
關鍵的 JNI 程式碼(開啟並配置串口):
int fd;
speed_t speed;
jobject mFileDescriptor;
/* Check arguments */
{
speed = getBaudrate(baudrate);
if (speed == -1) {
LOGE("Invalid baudrate");
return NULL;
}
}
/* Opening device */
{
jboolean iscopy;
const char *path_utf = (*env)->GetStringUTFChars(env, path, &iscopy);
LOGD("Opening serial port %s with flags 0x%x", path_utf, O_RDWR | flags);
fd = open(path_utf, O_RDWR | flags);
LOGD("open() fd = %d", fd);
(*env)->ReleaseStringUTFChars(env, path, path_utf);
if (fd == -1)
{
LOGE("Cannot open port");
return NULL;
}
}
/* Configure device */
{
struct termios cfg;
LOGD("Configuring serial port");
if (tcgetattr(fd, &cfg))
{
LOGE("tcgetattr() failed");
close(fd);
return NULL;
}
cfmakeraw(&cfg);
cfsetispeed(&cfg, speed);
cfsetospeed(&cfg, speed);
if (tcsetattr(fd, TCSANOW, &cfg))
{
LOGE("tcsetattr() failed");
close(fd);
return NULL;
}
}
文件描述符類的實例是與底層某種結構相關的不透明句柄,代表開放的檔案、socket 或字節來源/接收者。主要用途是建立 FileOutputStream 或 FileOutputStream。簡單來說,FileDescriptor 就是對一個檔案進行讀寫。
1)建工程:SerialDemo,包名 org.winplus.serial,並建立 jni、libs 兩個文件夾及 org.winplus.serial.utils。
2)SerialPortFinder 類:負責掃描 /proc/tty/drivers 找出所有串行動作。
package org.winplus.serial.utils;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Iterator;
import java.util.Vector;
import android.util.Log;
public class SerialPortFinder {
private static final String TAG = "SerialPort";
private Vector<Driver> mDrivers = null;
public class Driver {
public Driver(String name, String root) {
mDriverName = name;
mDeviceRoot = root;
}
private String mDriverName;
private String mDeviceRoot;
Vector<File> mDevices = null;
public Vector<File> getDevices() {
if (mDevices == null) {
mDevices = new Vector<File>();
File dev = new File("/dev");
File[] files = dev.listFiles();
int i;
for (i = 0; i < files.length; i++) {
if (files[i].getAbsolutePath().startsWith(mDeviceRoot)) {
Log.d(TAG, "Found new device: " + files[i]);
mDevices.add(files[i]);
}
}
}
return mDevices;
}
public String getName() {
return mDriverName;
}
}
Vector<Driver> getDrivers() throws IOException {
if (mDrivers == null) {
mDrivers = new Vector<Driver>();
LineNumberReader r = new LineNumberReader(new FileReader("/proc/tty/drivers"));
String l;
while ((l = r.readLine()) != null) {
// 由於 driver name 可能含空格,不能用 split() 提取
String drivername = l.substring(0, 0x15).trim();
String[] w = l.split(" +");
if ((w.length >= 5) && (w[w.length - 1].equals("serial"))) {
Log.d(TAG, "Found new driver " + drivername + " on " + w[w.length - 4]);
mDrivers.add(new Driver(drivername, w[w.length - 4]));
}
}
r.close();
}
return mDrivers;
}
public String[] getAllDevices() {
Vector<String> devices = new Vector<String>();
Iterator<Driver> itdriv;
try {
itdriv = getDrivers().iterator();
while (itdriv.hasNext()) {
Driver driver = itdriv.next();
Iterator<File> itdev = driver.getDevices().iterator();
while (itdev.hasNext()) {
String device = itdev.next().getName();
String value = String.format("%s (%s)", device, driver.getName());
devices.add(value);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return devices.toArray(new String[devices.size()]);
}
public String[] getAllDevicesPath() {
Vector<String> devices = new Vector<String>();
Iterator<Driver> itdriv;
try {
itdriv = getDrivers().iterator();
while (itdriv.hasNext()) {
Driver driver = itdriv.next();
Iterator<File> itdev = driver.getDevices().iterator();
while (itdev.hasNext()) {
String device = itdev.next().getAbsolutePath();
devices.add(device);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return devices.toArray(new String[devices.size()]);
}
}
3)SerialPort 類:負責加載 SO 檔,並透過 JNI 方式打開關閉串口。
package org.winplus.serial.utils;
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";
/* 不要刪除或改名 mFd 欄位,native close() 會用到 */
private FileDescriptor mFd;
private FileInputStream mFileInputStream;
private FileOutputStream mFileOutputStream;
public SerialPort(File device, int baudrate, int flags)
throws SecurityException, IOException {
/* Check access permission */
if (!device.canRead() || !device.canWrite()) {
try {
/* 缺少讀寫權限時,嘗試 chmod */
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;
}
// JNI
private native static FileDescriptor open(String path, int baudrate, int flags);
public native void close();
static {
System.loadLibrary("serial_port");
}
}
4)MyApplication:繼承 android.app.Application,負責串口的初始化與關閉。
package org.winplus.serial;
import java.io.File;
import java.io.IOException;
import java.security.InvalidParameterException;
import org.winplus.serial.utils.SerialPort;
import org.winplus.serial.utils.SerialPortFinder;
import android.content.SharedPreferences;
public class MyApplication extends android.app.Application {
public SerialPortFinder mSerialPortFinder = new SerialPortFinder();
private SerialPort mSerialPort = null;
public SerialPort getSerialPort() throws SecurityException, IOException, InvalidParameterException {
if (mSerialPort == null) {
/* 讀取串口參數 */
SharedPreferences sp = getSharedPreferences("android_serialport_api.sample_preferences", MODE_PRIVATE);
String path = sp.getString("DEVICE", "");
int baudrate = Integer.decode(sp.getString("BAUDRATE", "-1"));
/* Check parameters */
if ( (path.length() == 0) || (baudrate == -1)) {
throw new InvalidParameterException();
}
/* Open the serial port */
mSerialPort = new SerialPort(new File(path), baudrate, 0);
}
return mSerialPort;
}
public void closeSerialPort() {
if (mSerialPort != null) {
mSerialPort.close();
mSerialPort = null;
}
}
}
5)SerialPortActivity:抽象 Activity 類,負責讀取串口資訊。
package org.winplus.serial;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidParameterException;
import org.winplus.serial.utils.SerialPort;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
public abstract class SerialPortActivity extends Activity {
protected MyApplication mApplication;
protected SerialPort mSerialPort;
protected OutputStream mOutputStream;
private InputStream mInputStream;
private ReadThread mReadThread;
private class ReadThread extends Thread {
@Override
public void run() {
super.run();
while (!isInterrupted()) {
int size;
try {
byte[] buffer = new byte[64];
if (mInputStream == null)
return;
/* read 會一直等待數據,若要判斷是否接收完成,需設結束標識或做特殊處理 */
size = mInputStream.read(buffer);
if (size > 0) {
onDataReceived(buffer, size);
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}
private void DisplayError(int resourceId) {
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Error");
b.setMessage(resourceId);
b.setPositiveButton("OK", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SerialPortActivity.this.finish();
}
});
b.show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mApplication = (MyApplication) getApplication();
try {
mSerialPort = mApplication.getSerialPort();
mOutputStream = mSerialPort.getOutputStream();
mInputStream = mSerialPort.getInputStream();
/* Create a receiving thread */
mReadThread = new ReadThread();
mReadThread.start();
} catch (SecurityException e) {
DisplayError(R.string.error_security);
} catch (IOException e) {
DisplayError(R.string.error_unknown);
} catch (InvalidParameterException e) {
DisplayError(R.string.error_configuration);
}
}
protected abstract void onDataReceived(final byte[] buffer, final int size);
@Override
protected void onDestroy() {
if (mReadThread != null)
mReadThread.interrupt();
mApplication.closeSerialPort();
mSerialPort = null;
super.onDestroy();
}
}
6)編寫 string.xml 與 baudrates.xml:在 string.xml 加入三個錯誤提示:
<string name="error_configuration">Please configure your serial port first.</string> <string name="error_security">You do not have read/write permission to the serial port.</string> <string name="error_unknown">The serial port can not be opened for an unknown reason.</string>
並在 baudrates.xml 中定義 baudrates_name 與 baudrates_value 兩個字串陣列(從 50 到 4000000 的常見鮑率)。
7)編寫界面 main.xml:加入兩個編輯框,一個傳送命令、一個接收命令:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <EditText android:id="@+id/EditTextReception" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" android:gravity="top" android:hint="Reception" android:isScrollContainer="true" /> <EditText android:id="@+id/EditTextEmission" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Emission" android:lines="1" > </EditText> </LinearLayout>
8)SerialDemoActivity:繼承 SerialPortActivity,實作 onDataReceived 並在發送框按下時把資料寫入串口:
package org.winplus.serial;
import java.io.IOException;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class SerialDemoActivity extends SerialPortActivity{
EditText mReception;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mReception = (EditText) findViewById(R.id.EditTextReception);
EditText Emission = (EditText) findViewById(R.id.EditTextEmission);
Emission.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
int i;
CharSequence t = v.getText();
char[] text = new char[t.length()];
for (i=0; i<t.length(); i++) {
text[i] = t.charAt(i);
}
try {
mOutputStream.write(new String(text).getBytes());
mOutputStream.write('\n');
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
});
}
@Override
protected void onDataReceived(final byte[] buffer, final int size) {
runOnUiThread(new Runnable() {
public void run() {
if (mReception != null) {
mReception.append(new String(buffer, 0, size));
}
}
});
}
}
最後要实现 JNI 層:先編譯工程,在終端輸入 javah org.winplus.serial.utils.SerialPort 生成頭檔,命名為 SerialPort.h 複製到 jni 目錄,再新建 SerialPort.c 即可。
串口可用於掃描頭、指紋識別等周邊 USB 轉串口的特色應用。以上內容是對開源專案 android-serialport-api 的精簡說明,想深入了解的朋友可以研究該專案原始碼。
自定义 View 系列教程 05:两个经典示例的深度拆解
此前结合源码,我们分析完了自定义 View 的三个阶段:measure、layout、draw。那么,自定义 View 究竟有哪几种常见的方式呢? 一、直接继承自 Vi
如何替你的 Android APK 瘦身:實用的減重招式整理
APK 檔越來越大,已經是不爭的事實。Android 最初版本的時候,一個 App 的 APK 大約只有 2MB;到了現在,10MB 到 20MB 已是常態。造成這種爆炸
Android 網路開發入門:WebView、HttpURLConnection 與 HttpClient
這一章的目標很明確:讓 App 能透過 HTTP 與伺服器對話,並把回傳的資料解析成可用的內容。這是 Android 裡最基礎也最常用的一塊網路能力,我們從 WebVie
Android Fragment 與 Activity 間的資料傳遞(Fragment 取得資料)
Fragment 與 Activity 之間的資料交換大致分為三種:一、Fragment 從 Activity 取得資料;二、Activity 從 Fragment 取得