編輯:Android 開發實例
談到串口編程,就不得不提 JNI,以及 Java API 中的文件描述符類別 FileDescriptor。本文參考開源專案 android-serialport-api,對 JNI、FileDescriptor 與串口的相關知識及實作源碼做說明。
對於串口編程,我們只需對串口做一系列設定,然後打開串口,這些操作可參考串口調試助手的源碼。在 Java 中要實現串口的讀寫,只需操作檔案設備類別 FileDescriptor 即可,其他都交給驅動完成。本文不深入驅動,只略述應用層的實現方式。
libs/armeabi 資料夾,把 SO 檔 Copy 進去即可。libfilename.so(filename.so 為編譯後生成的檔名)。關鍵的 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;
}
}
文件描述符類別的實例作為與底層機器相關之某種結構的不透明 handle,代表開啟的檔案、socket 或字節來源/接收者。它的主要實際用途是建立 FileOutputStream 或 FileInputStream。簡單說,FileDescriptor 就是用來對檔案進行讀寫。
1)建工程:SerialDemo,並新建 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) {
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";
/* Do not remove or rename the field mFd: it is used by native method 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 {
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 繼承 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"));
if ( (path.length() == 0) || (baudrate == -1)) {
throw new InvalidParameterException();
}
mSerialPort = new SerialPort(new File(path), baudrate, 0);
}
return mSerialPort;
}
public void closeSerialPort() {
if (mSerialPort != null) {
mSerialPort.close();
mSerialPort = null;
}
}
}
5)新建抽象 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();
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 加入錯誤訊息字串,在 baudrates.xml 加入支援的鮑率清單(50 到 4000000 等,name 與 value 兩組陣列內容一致)。
7)編寫界面:在 main.xml 放兩個輸入框,一個傳送命令、一個接收命令。
8)SerialDemoActivity 的實作:
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 做了精簡,想深入了解的朋友可點擊原文連結。
Android 進度轉圈:ProgressBar Spinner 使用方式
在 Android 中,若背景任務需要一段時間完成,可以用 ProgressBar 提示使用者。Spinner 屬於不確定模式的進度條,適合無法預估完成時間的情境。 建立
Android 本地化:讓同一支 App 在不同語言環境下說不同的話
一支上架的 App,可能同時被義大利米蘭的使用者、日本東京的使用者、德國柏林的用戶打開。若所有文字都寫死在程式碼裡,海外市場就等於放棄。Android 對這件事有非常漂亮
Android 五種資料儲存方式全解析:SharedPreferences、檔案、SQLite、ContentProvider 與網路
資料儲存是開發中最頻繁面對的課題之一。Android 提供了多種互補的機制,本文逐一說明五種主要方式,並附上各自的關鍵程式碼與適用情境。 SharedPreferen
Android 載入 Spinner:不確定進度列的顯示與隱藏
在 Android 中,ProgressBar 可分為有明確進度的進度列,以及不確定進度的加載 Spinner。當任務耗時未知,例如等待網路回應,Spinner 很適合提