关于利用android-serialport-api实现在安卓设备上进行串口通信,附精简版demo,亲测可用。

来源:互联网 发布:mysql数据库zip下载 编辑:程序博客网 时间:2024/06/05 17:59

之前在网上找过相应的例子,但是在真实的安卓设备上都不能发送数据,弄得烦心,故自行下载google源码,弄了一个精简版。

所需设备:带有可用安卓设备一部,USB转串口线一条。用USB转串口线连接电脑,会提示你安装驱动,可用驱动精灵安装此驱动。驱动安装好后,电脑会虚拟出一个串口。


此为我虚拟出的串口,注意,COM1为电脑自带串口。另外笔记本没有自带串口。

以下为具体源码:

/* * Copyright 2009 Cedric Priscal *  * 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.  */package android_serialport_api.sample;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;public class MainMenu extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        //配置        final Button buttonSetup = (Button)findViewById(R.id.ButtonSetup);        buttonSetup.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {startActivity(new Intent(MainMenu.this, SerialPortPreferences.class));}});        //发送接收数据        final Button buttonConsole = (Button)findViewById(R.id.ButtonConsole);        buttonConsole.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {startActivity(new Intent(MainMenu.this, ConsoleActivity.class));}});        //批量发送,测试所用        final Button buttonSending = (Button)findViewById(R.id.ButtonSending);        buttonSending.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {startActivity(new Intent(MainMenu.this, SendingActivity.class));}});        //退出        final Button buttonQuit = (Button)findViewById(R.id.ButtonQuit);        buttonQuit.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {MainMenu.this.finish();}});    }}
此Activity不必多说,为应用主界面。


/* * Copyright 2009 Cedric Priscal *  * 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.  */package android_serialport_api.sample;import java.io.IOException;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class ConsoleActivity extends SerialPortActivity {EditText mReception;EditText Emission;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.console);mReception = (EditText) findViewById(R.id.EditTextReception);Emission = (EditText) findViewById(R.id.EditTextEmission);final Button buttonsend = (Button) findViewById(R.id.ButtonSent1);buttonsend.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {CharSequence t = Emission.getText();if (t.equals("")) {Toast.makeText(getApplicationContext(), "请输入发送的内容",Toast.LENGTH_SHORT).show();return;}char[] text = new char[t.length()];for (int 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();}}});}@Overrideprotected void onDataReceived(final byte[] buffer, final int size) {runOnUiThread(new Runnable() {public void run() {//if (mReception != null) {mReception.append(new String(buffer, 0, size));mReception.append("\n");//}}});}}

点击“发送数据”按钮后,跳转到此Activity。此Activity负责发送与接收数据。它继承了SerialPortActivity。SerialPortActivity负责打开所配置的串口。如下:

/* * Copyright 2009 Cedric Priscal *  * 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.  */package android_serialport_api.sample;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.security.InvalidParameterException;import android.app.Activity;import android.app.AlertDialog;import android.content.DialogInterface;import android.content.DialogInterface.OnClickListener;import android.os.Bundle;import android_serialport_api.SerialPort;public abstract class SerialPortActivity extends Activity {protected Application mApplication;protected SerialPort mSerialPort;protected OutputStream mOutputStream;private InputStream mInputStream;private ReadThread mReadThread;private class ReadThread extends Thread {@Overridepublic void run() {super.run();while (!isInterrupted()) {int size;try {byte[] buffer = new byte[64];if (mInputStream == null) {return;}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();}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);mApplication = (Application) 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);@Overrideprotected void onDestroy() {if (mReadThread != null)mReadThread.interrupt();mApplication.closeSerialPort();mSerialPort = null;super.onDestroy();}}

可以看出,此Activity利用Application类中的getSerialPort()方法打开串口,getOutputStream()、getInputStream()得到输出输入流。

Application类如下:

/* * Copyright 2009 Cedric Priscal *  * 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.  */package android_serialport_api.sample;import java.io.File;import java.io.IOException;import java.security.InvalidParameterException;import android.content.SharedPreferences;import android_serialport_api.SerialPort;import android_serialport_api.SerialPortFinder;public class Application extends android.app.Application {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);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("/dev/ttySAC1"), 9600, 0);mSerialPort = new SerialPort(new File(path), baudrate, 0);}return mSerialPort;}public void closeSerialPort() {if (mSerialPort != null) {mSerialPort.close();mSerialPort = null;}}}

应用中主要的就是这些,也比较显浅,很容易看懂。另外,android-serialport-api核心为SerialPortFinder和SerialPort类,负责得到设备中的所以串口以及打开串口。此处就不发出来了。demo中有,也很易懂。

以下引用http://blog.csdn.net/akunainiannian/article/details/8740007中的一句话:

android 串口,就不得不提JNI技术,它使得java中可以调用c语言写成的库。为可在android中使用串口,android-serialport-api的作者自己写了一个c语言的动态链接库serial_port.so(自动命名成libserial_port.so),并把它放在了libs/aemeabi 里,其c源文件在JNI中,大家在下载了android-serialport-api的源代码后,将这两个文件夹copy到自己新建的工程中即可。

真实设备上运行的情况,有图有真相:(接收区中set数据那里有点问题,由于我自己用不到接收,所以就不改了,需要的自己改一下,很简单。在ConsoleActivity 中)



DEMO下载地址:http://download.csdn.net/detail/ckw474404603/7637061


1 0