当前位置:首页 » 安卓系统 » android串口编程

android串口编程

发布时间: 2022-11-28 11:16:21

Ⅰ android_studio手机蓝牙串口通信源代码

初涉android的蓝牙操作,按照固定MAC地址连接获取Device时,程序始终是异常终止,查了好多天代码都没查出原因。今天改了一下API版本,突然就成功连接了。总结之后发现果然是个坑爹之极的错误。

为了这种错误拼命查原因浪费大把时间是非常不值得的,但是问题不解决更是揪心。可惜我网络了那么多,都没有给出确切原因。今天特此mark,希望后来者遇到这个问题的时候能轻松解决。

下面是我的连接过程,中间崩溃原因及解决办法。

1:用AT指令获得蓝牙串口的MAC地址,地址是简写的,按照常理猜测可得标准格式。

2:开一个String adress= "************" //MAC地址, String MY_UUID= "************"//UUID根据通信而定,网上都有。

3:取得本地Adapter用getDefaultAdapter(); 远程的则用getRemoteDevice(adress); 之后便可用UUID开socket进行通信。

如果中途各种在getRemoteDevice处崩溃,大家可以查看一下当前的API版本,如果是2.1或以下版本的话,便能确定是API版本问题,只要换成2.2或者以上就都可以正常运行了~ 这么坑爹的错误的确很为难初学者。 唉·········· 为这种小trick浪费很多时间真是难过。

(另外有个重要地方,别忘了给manifest里面加以下两个蓝牙操作权限哦~)

  • <uses-permissionandroid:name="android.permission.BLUETOOTH"></uses-permission>

  • <uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN"></uses-permission>

  • 下面附上Android蓝牙操作中用固定MAC地址传输信息的模板,通用搜索模式日后再补删模板:

  • =null;

  • =null;

  • privateOutputStreamoutStream=null;

  • privateInputStreaminStream=null;

  • privatestaticfinalUUIDMY_UUID=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//这条是蓝牙串口通用的UUID,不要更改

  • privatestaticStringaddress="00:12:02:22:06:61";//<==要连接的蓝牙设备MAC地址

  • /*获得通信线路过程*/

  • /*1:获取本地BlueToothAdapter*/

  • mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();

  • if(mBluetoothAdapter==null)

  • {

  • Toast.makeText(this,"Bluetoothisnotavailable.",Toast.LENGTH_LONG).show();

  • finish();

  • return;

  • }

  • if(!mBluetoothAdapter.isEnabled())

  • {

  • Toast.makeText(this,"-runthisprogram.",Toast.LENGTH_LONG).show();

  • finish();

  • return;

  • }

  • /*2:获取远程BlueToothDevice*/

  • BluetoothDevicedevice=mBluetoothAdapter.getRemoteDevice(address);

  • if(mBluetoothAdapter==null)

  • {

  • Toast.makeText(this,"Can'tgetremotedevice.",Toast.LENGTH_LONG).show();

  • finish();

  • return;

  • }

  • /*3:获得Socket*/

  • try{

  • btSocket=device.(MY_UUID);

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:Socketcreationfailed.",e);

  • }

  • /*4:取消discovered节省资源*/

  • mBluetoothAdapter.cancelDiscovery();

  • /*5:连接*/

  • try{

  • btSocket.connect();

  • Log.e(TAG,"ONRESUME:BTconnectionestablished,datatransferlinkopen.");

  • }catch(IOExceptione){

  • try{

  • btSocket.close();

  • }catch(IOExceptione2){

  • Log.e(TAG,"ONRESUME:",e2);

  • }

  • }

  • /*此时可以通信了,放在任意函数中*/

  • /*try{

  • outStream=btSocket.getOutputStream();

  • inStream=btSocket.getInputStream();//可在TextView里显示

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:Outputstreamcreationfailed.",e);

  • }

  • Stringmessage="1";

  • byte[]msgBuffer=message.getBytes();

  • try{

  • outStream.write(msgBuffer);

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:Exceptionringwrite.",e);

  • }

  • */

  • 通用搜索模式代码模板:

    简洁简洁方式1 demo


    作用: 用VerticalSeekBar控制一个 LED屏幕的亮暗。

    直接上码咯~

  • packagecom.example.seed2;

  • importandroid.app.Activity;

  • importandroid.app.AlertDialog;

  • importandroid.app.Dialog;

  • importandroid.os.Bundle;

  • importjava.io.IOException;

  • importjava.io.InputStream;

  • importjava.io.OutputStream;

  • importjava.util.UUID;

  • importandroid.bluetooth.BluetoothAdapter;

  • importandroid.bluetooth.BluetoothDevice;

  • importandroid.bluetooth.BluetoothSocket;

  • importandroid.content.DialogInterface;

  • importandroid.util.Log;

  • importandroid.view.KeyEvent;

  • importandroid.widget.Toast;

  • {

  • privatestaticfinalStringTAG="BluetoothTest";

  • =null;

  • =null;

  • privateOutputStreamoutStream=null;

  • privateInputStreaminStream=null;

  • privateVerticalSeekBarvskb=null;

  • privatestaticfinalUUIDMY_UUID=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//这条是蓝牙串口通用的UUID,不要更改

  • privatestaticStringaddress="00:12:02:22:06:61";//<==要连接的蓝牙设备MAC地址

  • /**.*/

  • @Override

  • publicvoidonCreate(BundlesavedInstanceState){

  • super.onCreate(savedInstanceState);

  • setContentView(R.layout.main);

  • this.vskb=(VerticalSeekBar)super.findViewById(R.id.mskb);

  • this.vskb.setOnSeekBarChangeListener(newOnSeekBarChangeListenerX());

  • mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();

  • if(mBluetoothAdapter==null)

  • {

  • Toast.makeText(this,"Bluetoothisnotavailable.",Toast.LENGTH_LONG).show();

  • finish();

  • return;

  • }

  • if(!mBluetoothAdapter.isEnabled())

  • {

  • Toast.makeText(this,"-runthisprogram.",Toast.LENGTH_LONG).show();

  • finish();

  • return;

  • }

  • }

  • .OnSeekBarChangeListener{

  • publicvoidonProgressChanged(VerticalSeekBarseekBar,intprogress,booleanfromUser){

  • //Main.this.clue.setText(seekBar.getProgress());

  • /*Stringmessage;

  • byte[]msgBuffer;

  • try{

  • outStream=btSocket.getOutputStream();

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:OutputStreamcreationfailed.",e);

  • }

  • message=Integer.toString(seekBar.getProgress());

  • msgBuffer=message.getBytes();

  • try{

  • outStream.write(msgBuffer);

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:Exceptionringwrite.",e);

  • }*/

  • }

  • (VerticalSeekBarseekBar){

  • Stringmessage;

  • byte[]msgBuffer;

  • try{

  • outStream=btSocket.getOutputStream();

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:OutputStreamcreationfailed.",e);

  • }

  • message=Integer.toString(seekBar.getProgress());

  • msgBuffer=message.getBytes();

  • try{

  • outStream.write(msgBuffer);

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:Exceptionringwrite.",e);

  • }

  • }

  • publicvoidonStopTrackingTouch(VerticalSeekBarseekBar){

  • Stringmessage;

  • byte[]msgBuffer;

  • try{

  • outStream=btSocket.getOutputStream();

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:OutputStreamcreationfailed.",e);

  • }

  • message=Integer.toString(seekBar.getProgress());

  • msgBuffer=message.getBytes();

  • try{

  • outStream.write(msgBuffer);

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:Exceptionringwrite.",e);

  • }

  • }

  • }

  • @Override

  • publicvoidonStart()

  • {

  • super.onStart();

  • }

  • @Override

  • publicvoidonResume()

  • {

  • super.onResume();

  • BluetoothDevicedevice=mBluetoothAdapter.getRemoteDevice(address);

  • try{

  • btSocket=device.(MY_UUID);

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:Socketcreationfailed.",e);

  • }

  • mBluetoothAdapter.cancelDiscovery();

  • try{

  • btSocket.connect();

  • Log.e(TAG,"ONRESUME:BTconnectionestablished,datatransferlinkopen.");

  • }catch(IOExceptione){

  • try{

  • btSocket.close();

  • }catch(IOExceptione2){

  • Log.e(TAG,"ONRESUME:",e2);

  • }

  • }

  • //.

  • /*try{

  • outStream=btSocket.getOutputStream();

  • inStream=btSocket.getInputStream();

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:Outputstreamcreationfailed.",e);

  • }

  • Stringmessage="read";

  • byte[]msgBuffer=message.getBytes();

  • try{

  • outStream.write(msgBuffer);

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:Exceptionringwrite.",e);

  • }

  • intret=-1;

  • while(ret!=-1)

  • {

  • try{

  • ret=inStream.read();

  • }catch(IOExceptione)

  • {

  • e.printStackTrace();

  • }

  • }

  • */

  • }

  • @Override

Ⅱ 我想用Android手机与单片机进行串口通信,从而可以控制单片机,怎么实现

代码不会写!但是给你个思路:

1、单片机串口转WIFI了,那么WIFI传出来的数据,手机接收到要有软件解码识别它
2、手机软件通过WIFI将数据传到单片机,这样交互就可以通信了。控制协议可以自己设定。

Ⅲ Android平台到底能不能通过串口发送AT指令呢,急!!!

AT命令(Attention)在手机中,用于对modem(也就是移动模块)通过串口命令进行操作,处理与语音电话、短信和数据。

关于AT命令:

  1. Android系统与AT命令

    对于智能手机,AP和BP分离的情况,在AP上的系统通过串口和BP通信是个不错方式。在Android的源码中有一个内部包com.android.internal.telephony中有对AT命令的封装和解析,但这种internal的包开发者不能调用的SDK部分,可以用来封装ROM。这说明Android对AT command的方式是支持的。

  2. 对于Android如何调用AT command

    用root登录命令行,直接对串口进行操作,如echo -e "AT " > /dev/smd0

    具体的串口,不同设备会有不同,甚至不一定会提供。这种方式,开发者是可以调用的,通过Runtime.exec直接执行命令行命令,但要求是root,例如echo -e "ATD123456789; " > /dev/smd0,拨打123456789的号码。

  3. 目前最新的AT命令标准发布与2014.6.27,似乎还活得挺滋润的。但是给出的keywords是UMTS, GSM, command, terminal, LTE这说明CDMA确实很可能不是采用AT命令的方式。

Ⅳ android蓝牙开发,PC端模拟串口接收字符,该如何编程

您好,android蓝牙这方面还是很好搞的,因为大家的方式都是差不多的。先说说如何开启蓝牙设备和设置可见时间:

private void search() {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (!adapter.isEnabled()) {
adapter.enable();
}
Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600); //3600为蓝牙设备可见时间
startActivity(enable);
Intent searchIntent = new Intent(this, ComminuteActivity.class);
startActivity(searchIntent);
}

首先,需要获得一个BluetoothAdapter,可以通过getDefaultAdapter()获得系统默认的蓝牙适配器,当然我们也可以自己指定,但这个真心没有必要,至少我是不需要的。然后我们检查手机的蓝牙是否打开,如果没有,通过enable()方法打开。接着我们再设置手机蓝牙设备的可见,可见时间可以自定义。

完成这些必要的设置后,我们就可以正式开始与蓝牙模块进行通信了:

public class ComminuteActivity extends Activity {
private BluetoothReceiver receiver;
private BluetoothAdapter bluetoothAdapter;
private List<String> devices;
private List<BluetoothDevice> deviceList;
private Bluetooth client;
private final String lockName = "BOLUTEK";
private String message = "000001";
private ListView listView;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);

listView = (ListView) this.findViewById(R.id.list);
deviceList = new ArrayList<BluetoothDevice>();
devices = new ArrayList<String>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
receiver = new BluetoothReceiver();
registerReceiver(receiver, filter);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
setContentView(R.layout.connect_layout);
BluetoothDevice device = deviceList.get(position);
client = new Bluetooth(device, handler);
try {
client.connect(message);
} catch (Exception e) {
Log.e("TAG", e.toString());
}
}
});
}

@Override
protected void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}

private final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Bluetooth.CONNECT_FAILED:
Toast.makeText(ComminuteActivity.this, "连接失败", Toast.LENGTH_LONG).show();
try {
client.connect(message);
} catch (Exception e) {
Log.e("TAG", e.toString());
}
break;
case Bluetooth.CONNECT_SUCCESS:
Toast.makeText(ComminuteActivity.this, "连接成功", Toast.LENGTH_LONG).show();
break;
case Bluetooth.READ_FAILED:
Toast.makeText(ComminuteActivity.this, "读取失败", Toast.LENGTH_LONG).show();
break;
case Bluetooth.WRITE_FAILED:
Toast.makeText(ComminuteActivity.this, "写入失败", Toast.LENGTH_LONG).show();
break;
case Bluetooth.DATA:
Toast.makeText(ComminuteActivity.this, msg.arg1 + "", Toast.LENGTH_LONG).show();
break;
}
}
};

private class BluetoothReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (isLock(device)) {
devices.add(device.getName());
}
deviceList.add(device);
}
showDevices();
}
}

private boolean isLock(BluetoothDevice device) {
boolean isLockName = (device.getName()).equals(lockName);
boolean isSingleDevice = devices.indexOf(device.getName()) == -1;
return isLockName && isSingleDevice;
}

private void showDevices() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
devices);
listView.setAdapter(adapter);
}
}

Ⅳ android虚拟机串口通信

工具:Virtual Serial Port Driver.
用这个工具虚拟出一对串口。
下载地址

2.用串口调试助手,测试串口通信。
3.用这个命令启动虚拟机:emulator @2.2 -scale auto -qemu -serial COM3 &
说明:
2.2:是虚拟机的名称。
COM3是你要选择的串口。
ps:在cmd中使用这个命令有两种方式:1)将安卓的sdk的tools文件夹加入到path环境变量中,2)在安卓的sdk的tools文件夹下打开cmd。
4.虚拟机中测试串口通信用谷歌的一个开源项目:android_serialport_api
5.在虚拟机中运行项目。
说明:运行前要获取设备的权限
1)在cmd中用adb shell命令,进入虚拟机命令行环境。

2)打开dev文件夹:cd dev
3)获取权限:chmod 777 ttyS2

6.谷歌的开源项目不能导入进eclipse,我整理了一下,调通了。

Ⅵ android如何读取串口数据

楼主问题解决了没?我用串口调试助手调试,安卓端能发送数据到pc端接收,但反过来pc端发数据过来安卓无法接收,求大神指导啊

Ⅶ 我想用Android手机与单片机进行串口通信,从而可以控制单片机,该如何实现呢

不过你还得注意的是手机的USB转串口电平是TTL电平,所以你的单片机板子的串口也得是TTL,在就是分清楚交叉连接或者直连。

Ⅷ 谁有没有Android串口的使用例子

1 首先做的是创建新的工程然后添加一下文件


3代码

好了 然后就是关于这个页面的Code了,

这是我的:

package android.serialport;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.BreakIterator;
import java.util.ServiceConfigurationError;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MyserialActivity extendsActivity
{
EditText sendedit;
EditText receiveedit;
FileInputStream mInStream;
FileOutputStream mOutStream;
SerialPort classserialport;
ReadThread mReadThread;

private class ReadThread extends Thread
{
public void run()
{
super.run();
while(!isInterrupted())
{
int size;
}
}
}


void onDataReceive(final byte[] buffer,finalint size)
{
runOnUiThread(new Runnable()
{

@Override
publicvoid run()
{
// TODO Auto-generated method stub
if(mReadThread != null)
{
receiveedit.append(newString(buffer,0,size));
}
}
});
}
@Override
protectedvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_myserial);

sendedit= (EditText)findViewById(R.id.editText1);
receiveedit=(EditText)findViewById(R.id.editText2);


receiveedit.setFocusable(false);//进制输入
/*
* 打开串口
* */
finalButton openserial =(Button)findViewById(R.id.button1);
openserial.setOnClickListener(newView.OnClickListener()
{

@Override
publicvoid onClick(View arg0)
{
//TODO Auto-generated method stub
try
{
classserialport=new SerialPort(new File("/dev/ttyS2"),9600);
}catch(SecurityExceptione)
{
e.printStackTrace();
}
catch(IOExceptione)
{
e.printStackTrace();
}
mInStream=(FileInputStream) classserialport.getInputStream();
Toast.makeText(MyserialActivity.this,"串口打开成功",Toast.LENGTH_SHORT).show();
}
});
/*
* 发送数据
* */
finalButton sendButton =(Button)findViewById(R.id.button2);
sendButton.setOnClickListener(newView.OnClickListener()
{

@Override
publicvoid onClick(View arg0)
{

Stringindata;
indata=sendedit.getText().toString();
//TODO Auto-generated method stub
try
{
mOutStream=(FileOutputStream) classserialport.getOutputStream();
mOutStream.write(indata.getBytes());
mOutStream.write(' ');
}
catch(IOExceptione)
{
e.printStackTrace();
}
Toast.makeText(MyserialActivity.this,"数据发送成功",Toast.LENGTH_SHORT).show();
sendedit.setText("");
}
});
/*
* 接收数据
* */
finalButton receButton= (Button)findViewById(R.id.button3);
receButton.setOnClickListener(newView.OnClickListener()
{//inttag =0;

@Override
publicvoid onClick(View arg0)
{
// TODO Auto-generated method stub
intsize;
try
{
byte[]buffer = new byte[64];
if(mInStream== null) return;
size= mInStream.read(buffer);
if(size>0)
{
receiveedit.setText("");

}
if(size>0)
{
onDataReceive(buffer,size);
}
inttag =1;

receiveedit.setText(newString(buffer, 0, size));

}catch(IOExceptione)
{
e.printStackTrace();
return;
}
}

privateboolean isInterrupted()
{
// TODO Auto-generated methodstub
returnfalse;
}
});
/*
* 清楚接收区
* */
finalButton ClearButton = (Button)findViewById(R.id.clear);
ClearButton.setOnClickListener(newView.OnClickListener()
{

@Override
publicvoid onClick(View arg0)
{
//TODO Auto-generated method stub
receiveedit.setText("");
}
});}

@Override
publicboolean onCreateOptionsMenu(Menu menu)
{
//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.myserial,menu);
returntrue;
}

}

好吧 你做好了。

3需要加载的文件

下面我把所需要添加的代码贴一贴

第一个是Serialport.java

/*
* 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 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;

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; //创建一个文件描述符对象 mFd
private FileInputStream mFileInputStream;
private FileOutputStream mFileOutputStream;

public SerialPort(File device, int baudrate) throws SecurityException, IOException {
/*
* 检查访问权限
* */
/* Check access permission */
if (!device.canRead() || !device.canWrite()) {//如果设备不可读或者设备不可写
try {
/* Missing read/write permission, trying to chmod the file *///没有读写权限,就尝试去挂载权限
Process su; //流程进程 su
su = Runtime.getRuntime().exec("/system/bin/su");//通过执行挂载到/system/bin/su 获得执行
String cmd = "chmod 777 " + device.getAbsolutePath() + " "
+ "exit ";
/*String cmd = "chmod 777 /dev/s3c_serial0" + " "
+ "exit ";*/
su.getOutputStream().write(cmd.getBytes());//进程。获得输出流。写(命令。获得二进制)
if ((su.waitFor() != 0) || !device.canRead()
|| !device.canWrite()) {//如果 进程等待不是0 或者 设备不能读写就
throw new SecurityException();//抛出一个权限异常
}
} catch (Exception e) {
e.printStackTrace();
throw new SecurityException();
}
}
/*
*
* */
mFd = open(device.getAbsolutePath(), baudrate);
//device.getAbsolutePath()这是要挂载的路径new File("/dev/ttyS2")
if (mFd == null) {
Log.e(TAG, "native open returns null");
throw new IOException();//输入输出异常
}
//将文件描述符 做输入输出流的参数 传递给创建的输入输出流
mFileInputStream = new FileInputStream(mFd);
mFileOutputStream = new FileOutputStream(mFd);
}

// Getters and setters
public InputStream getInputStream() {
return mFileInputStream;
}

public OutputStream getOutputStream() {
return mFileOutputStream;
}

// JNI
private native static FileDescriptor open(String path, int baudrate);
public native void close();
static {
System.loadLibrary("serial_port");
}
}

第二个是SerialPortFinder.java

/*
* 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 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;

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 {

/*
* 创建一个驱动程序类
* */
public class Driver {
public Driver(String name, String root) {
mDriverName = name;//String 类型的
mDeviceRoot = root;
}
private String mDriverName;
private String mDeviceRoot;
Vector<File> mDevices = null;
/*
* Vector 类在 java 中可以实现自动增长的对象数组
* 简单的使用方法如下:
vector<int> test;//建立一个vector
test.push_back(1);
test.push_back(2);//把1和2压入vector这样test[0]就是1,test[1]就是2
* */
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;
}
}
/*
*
*
* */
private static final String TAG = "SerialPort";

private Vector<Driver> mDrivers = null;

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[] w = l.split(" +");
if ((w.length == 5) && (w[4].equals("serial"))) {
Log.d(TAG, "Found new driver: " + w[1]);
mDrivers.add(new Driver(w[0], w[1]));
}
}
r.close();
}
return mDrivers;
}

public String[] getAllDevices() {
Vector<String> devices = new Vector<String>();
// Parse each driver
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>();
// Parse each driver
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()]);
}
}

第三个是Android.mk

#
# 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 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.
#

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

TARGET_PLATFORM := android-3
LOCAL_MODULE := serial_port
LOCAL_SRC_FILES := SerialPort.c
LOCAL_LDLIBS := -llog

include $(BUILD_SHARED_LIBRARY)

第四个是SerialPort.c

/*
* 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 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.
*/

#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <jni.h>

#include "android/log.h"
static const char *TAG="serial_port";
#define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO, TAG, fmt, ##args)
#define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, TAG, fmt, ##args)
#define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, TAG, fmt, ##args)

static speed_t getBaudrate(jint baudrate)
{
switch(baudrate) {
case 0: return B0;
case 50: return B50;
case 75: return B75;
case 110: return B110;
case 134: return B134;
case 150: return B150;
case 200: return B200;
case 300: return B300;
case 600: return B600;
case 1200: return B1200;
case 1800: return B1800;
case 2400: return B2400;
case 4800: return B4800;
case 9600: return B9600;
case 19200: return B19200;
case 38400: return B38400;
case 57600: return B57600;
case 115200: return B115200;
case 230400: return B230400;
case 460800: return B460800;
case 500000: return B500000;
case 576000: return B576000;
case 921600: return B921600;
case 1000000: return B1000000;
case 1152000: return B1152000;
case 1500000: return B1500000;
case 2000000: return B2000000;
case 2500000: return B2500000;
case 3000000: return B3000000;
case 3500000: return B3500000;
case 4000000: return B4000000;
default: return -1;
}
}

/*
* Class: cedric_serial_SerialPort
* Method: open
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT jobject JNICALL Java_android_serialport_SerialPort_open
(JNIEnv *env, jobject thiz, jstring path, jint baudrate)
{
int fd;
speed_t speed;
jobject mFileDescriptor;

/* Check arguments */
{
speed = getBaudrate(baudrate);
if (speed == -1) {
/* TODO: throw an exception */
LOGE("Invalid baudrate");
return NULL;
}
}

/* Opening device */
{
jboolean is;
const char *path_utf = (*env)->GetStringUTFChars(env, path, &is);
LOGD("Opening serial port %s", path_utf);
fd = open(path_utf, O_RDWR | O_DIRECT | O_SYNC);
LOGD("open() fd = %d", fd);
(*env)->ReleaseStringUTFChars(env, path, path_utf);
if (fd == -1)
{
/* Throw an exception */
LOGE("Cannot open port");
/* TODO: throw an exception */
return NULL;
}
}

/* Configure device */
{
struct termios cfg;
LOGD("Configuring serial port");
if (tcgetattr(fd, &cfg))
{
LOGE("tcgetattr() failed");
close(fd);
/* TODO: throw an exception */
return NULL;
}

cfmakeraw(&cfg);
cfsetispeed(&cfg, speed);
cfsetospeed(&cfg, speed);

if (tcsetattr(fd, TCSANOW, &cfg))
{
LOGE("tcsetattr() failed");
close(fd);
/* TODO: throw an exception */
return NULL;
}
}

/* Create a corresponding file descriptor */
{
jclass cFileDescriptor = (*env)->FindClass(env, "java/io/FileDescriptor");
jmethodID iFileDescriptor = (*env)->GetMethodID(env, cFileDescriptor, "<init>", "()V");
jfieldID descriptorID = (*env)->GetFieldID(env, cFileDescriptor, "descriptor", "I");
mFileDescriptor = (*env)->NewObject(env, cFileDescriptor, iFileDescriptor);
(*env)->SetIntField(env, mFileDescriptor, descriptorID, (jint)fd);
}

return mFileDescriptor;
}

/*
* Class: cedric_serial_SerialPort
* Method: close
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_android_serialport_SerialPort_close
(JNIEnv *env, jobject thiz)
{
jclass SerialPortClass = (*env)->GetObjectClass(env, thiz);
jclass FileDescriptorClass = (*env)->FindClass(env, "java/io/FileDescriptor");

jfieldID mFdID = (*env)->GetFieldID(env, SerialPortClass, "mFd", "Ljava/io/FileDescriptor;");
jfieldID descriptorID = (*env)->GetFieldID(env, FileDescriptorClass, "descriptor", "I");

jobject mFd = (*env)->GetObjectField(env, thiz, mFdID);
jint descriptor = (*env)->GetIntField(env, mFd, descriptorID);

LOGD("close(fd = %d)", descriptor);
close(descriptor);
}

Ⅸ Android平台的串口通信技术

如下表不同操作系统的串口地址,Android是基于Linux的所以一般情况下使用Android系统的设备串口地址为/dev/ttyS0...

Ⅹ Android UART 串口通信

最近有项目需要实现windows机器和Android开发版进行UART串口通信,经过3天查找尝试,特记录一下最终方案,希望之后的同行少走弯路,最后在git上回开源我最终的方案希望大家支持。

Android 3.0.1
Gradle 4.1
ARM开发版 : RK3399
PC机器:Win10
开发机器:MAC 10.13.3

先上图

由于 android-serialport-api 项目中的so使用较old的ndk编译,所以在对于Android 6.0 以上版本兼容的时候会报错 dlopen failed: "has text relocations" 。且使用的mk进行编译,特升级为用cmake编译。

升级 android-serialport-api

项目结构:

app对应原项目中的各个Activity, androidserial 是mole 对应编译之前的so,还有API的封装。可以直接引用androidserial,调用方法参考app目录下的activity。

注意 关于权限!

当接入开发板后如果发现 Error You do not have read/write permission to the serial port 需要root 权限 ,在开发者模式中开启root 权限 adb和应用

使用一下命令开启Android对串口的读写权限

setenforce 0 : 关闭防火墙,有人说关键是这,但是我的环境不用关闭,只要给权限就可以

注意 关于ttyS1 - 6 ttyS1 - 6 对应的是 UART 串口1-6 一般都是一一对应的。这个具体要看一下开发板的说明。

记录的比较糙,还请见谅,如有问题请留言,我看到后肯定回复。项目主要看结构,剩下的都是复制黏贴的事。 git地址:https://github.com/braincs/AndroidSerialLibrary

热点内容
phplinux服务器 发布:2024-05-02 20:30:23 浏览:754
安卓在哪里安装网易官方手游 发布:2024-05-02 20:15:07 浏览:408
qq宠物的文件夹 发布:2024-05-02 20:13:46 浏览:366
做脚本挂 发布:2024-05-02 19:09:14 浏览:931
打王者开最高配置哪个手机好 发布:2024-05-02 19:08:31 浏览:351
python字典使用 发布:2024-05-02 19:01:14 浏览:134
我的世界服务器联机ip 发布:2024-05-02 18:50:39 浏览:619
steam密码从哪里看 发布:2024-05-02 18:50:00 浏览:629
convertlinux 发布:2024-05-02 18:20:00 浏览:705
zxingandroid简化 发布:2024-05-02 17:47:53 浏览:189