WEB开发网
开发学院手机开发Android 开发 Android 串行接口(serial port)编程 阅读

Android 串行接口(serial port)编程

 2013-03-12 15:26:28 来源:开发学院   
核心提示: 利用开源的android-serialport-api项目(http://code.google.com/p/android-serialport-api/),重新连接usb线到Adapter(USB to RS232 adapters,Android 串行接口(serial port)编程,参考http://cod

 利用开源的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
 
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;


	@Override
	public 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 stub
		return null;
	}
	
	
	//for serial port
	public 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;
		}
	}



	
}

1 2 3  下一页

Tags:Android 串行 接口

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接