之前在网上找过相应的例子,但是在真实的安卓设备上都不能发送数据,弄得烦心,故自行下载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) {
startA