Android 串行接口(serial port)编程
本例子来自实际的出租车项目,背景:客户下载Android/iOS客户端订车系统,出租车司机的Driver系统接受订单后,驾驶至目的地,客户上车,计价器off/on,客户下车。Android程序需要读取计价器的off/on状态,进行后继处理。解决方案:利用开源的android-serialport-api项目(http://code.google.com/p/android-serialport-api/),重新连接usb线到Adapter(USB to RS232 adapters,参考http://code.google.com/p/android-serialport-api/wiki/android_to_rs232_guideline?tm=6。),连接后如下图:
编码:android-serialport-api项目包装了串行接口的通讯,因此我们不需要关心jni的调用等一系列的过程。自带的sample实例,演示了怎样读取串行口的信号码,代码也比较简单,稍微修改拿过来使用即可。直接上代码SerialApplication.java[java]package com.whyonly.serial;import java.io.File;import java.io.IOException;import java.security.InvalidParameterException;import android.app.Application;import android.content.SharedPreferences;import android.location.Location;import android.preference.PreferenceManager;import android.util.Log;import android_serialport_api.SerialPort;import android_serialport_api.SerialPortFinder;public class SerialApplication extends Application{private static final String TAG = "SerialApplication";private SharedPreferences mPrefs;@Overridepublic void onCreate(){Log.d(TAG,"load....");super.onCreate();//will save the values to Preference later.mPrefs = PreferenceManager.getDefaultSharedPreferences(this);}public SharedPreferences getmPrefs() {return mPrefs;}public String getUserId() {// TODO Auto-generated method stubreturn null;}//for serial portpublic SerialPortFinder mSerialPortFinder = new SerialPortFinder();private SerialPort mSerialPort = null;public SerialPort getSerialPort() throws SecurityException, IOException, InvalidParameterException {if (mSerialPort == null) {/* Read serial port parameters *///SharedPreferences sp = getSharedPreferences("android_serialport_api.sample_preferences", MODE_PRIVATE);SharedPreferences sp = ((SerialApplication)this.getApplicationContext()).getmPrefs();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;}}}MainActivity.java[java]package com.whyonly.serial;import android.os.Bundle;import android.app.Activity;import android.util.Log;import android.view.Menu;public class MainActivity extends Activity {private static final String TAG = "MainActivity";private USBSerialHelper usbSerialHelper;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);补充:移动开发 , Android ,