最近有个项目,要使用android设备操作串口的 斑马GK888T打印机,使用打印机打印二维码。

硬件设备连接方式:

安卓设备 通过 串口RS232 连接 斑马打印机的串口

那么就要解决:使用安卓设备操作串口的问题。 我找到一个框架:android_serialport_api,这个框架被托管在:

https://code.google.com/p/android-serialport-api/    谷歌的代码库,无奈国内无法下载

https://github.com/cepr/android-serialport-api     GITHUB的地址,这个可以下载

下载后,阅读下源代码,准备使用。

1.拷贝 jni 文件夹下的文件到 你的project中, 这些是jni调用的设定文件,包括:

  Android.mk

  Application.mk

  gen_SerialPort_h.sh

  SerialPort.c

  SerialPort.h

2.拷贝libs 下的文件到你的 project中,这些是原生库,包括

  armeabi/libserial_port.so

  armeabi-v7a/libserial_port.so

  x86/libserial_port.so

3.在你的项目下新建 package: android_serialport_api,拷贝下列src下的class  到这个package下

  Application.java

  SerialPort.java

  SerialPortActivity.java

  SerialPortFinder.java

  注意, package名称一定要是android_serialport_api。或者你需要修改Android.mk下对应的模块配置项。不然会提示找不到jni调用的库

4.拷贝资源文件等:

  string.xml 的内容:

    <string name="error_configuration">Please configure your serial port first.</string>
<string name="error_security">You do not have read/write permission to the serial
port.</string>
<string name="error_unknown">The serial port can not be opened for an unknown
reason.</string>

5.修改AndroidManifest.xml,在application节点指定对应的 "android:name" 配置,如下面红色文字所示

    <application
android:allowBackup="true"
android:name="android_serialport_api.Application"
android:theme="@style/AppTheme" >

6.下面写测试的activity。我的设备连接在安卓设备的端口 ”ttyS2”上,下面是个演示:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:keepScreenOn="true"
android:orientation="vertical" > <EditText
android:id="@+id/EditTextReception"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="7"
android:gravity="top"
android:hint="Reception"
android:isScrollContainer="true"
android:scrollbarStyle="insideOverlay" >
</EditText> <EditText
android:id="@+id/EditTextEmission"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Emission"
android:lines="4"
android:text="" >
</EditText> <Button
android:id="@+id/btnSend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Send" /> </LinearLayout>
/*
* 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 zyf.serialportdemo; import java.io.IOException; import zyf.serialportdemo.R; import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android_serialport_api.SerialPortActivity; public class ConsoleActivity extends SerialPortActivity {
Button btnSend;
EditText mReception;
EditText mEmission; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.console); // setTitle("Loopback test");
mReception = (EditText) findViewById(R.id.EditTextReception); mEmission = (EditText) findViewById(R.id.EditTextEmission); btnSend = (Button)findViewById(R.id.btnSend);
btnSend.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
String text = mEmission.getText().toString();
try {
mOutputStream.write(new String(text).getBytes());
mOutputStream.write('\n');
} catch (IOException e) {
e.printStackTrace();
}
}
});
//发送指令到斑马打印机
mEmission.setText("^XA^A0N,40,30^FO50,150^FDHELLO WORLD^FS^XZ");
    /*二维码指令

      ^XA
      ^PMY
      ^FO200,200^BQ,2,10
      ^FDD03040C,LA,012345678912AABBqrcode^FS
      ^XZ

    */
} @Override
protected void onDataReceived(final byte[] buffer, final int size) {
runOnUiThread(new Runnable() {
public void run() {
if (mReception != null) {
mReception.append(new String(buffer, 0, size));
}
}
});
}
}
/*
* 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; import java.io.File;
import java.io.IOException;
import java.security.InvalidParameterException; import android.content.SharedPreferences; 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", "");
//String path = "ttyS2";
String path = "/dev/ttyS2";//指定端口
//int baudrate = Integer.decode(sp.getString("BAUDRATE", "-1"));
int baudrate = 9600;//指定速率
/* 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;
}
}
}

最后别忘了一个操作权限的问题,很多设备直接操作串口,会提示无权限 read/write 的问题,需要java层去提权,方法如下:

使用下面的方法执行指令: chmod 777 /dev/ttyS2
public void exeShell(String cmd){        

            try{
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader in = new BufferedReader(
new InputStreamReader(
p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
Log.i("exeShell",line);
} }
catch(Throwable t)
{
t.printStackTrace();
}
}

手动解决方法:打开cmd,进入  adb shell,执行:chmod 777 /dev/ttyS2

 

参考:

https://code.google.com/p/android-serialport-api/

https://github.com/cepr/android-serialport-api

http://blog.csdn.net/imyang2007/article/details/8331800

http://blog.csdn.net/imyang2007/article/details/8331800

http://bbs.csdn.net/topics/380234030

android开发(37) android使用android_serialport_api 操作串口,解决权限问题的更多相关文章

  1. Android开发之使用sqlite3工具操作数据库的两种方式

    使用 sqlite3 工具操作数据库的两种方式 请尊重他人的劳动成果,转载请注明出处:Android开发之使用sqlite3工具操作数据库的两种方式 http://blog.csdn.net/feng ...

  2. Android开发华为手机无法看log日志解决方法

    Android开发华为手机无法看log日志解决方法 上班的时候,由于开发工具由Eclipse改成Android Studio后,原本的华为手机突然无法查看崩溃日志了,大家都知道,若是无法查看日志要它毛 ...

  3. AllJoyn+Android开发案例-android跨设备调用方法

    AllJoyn+Android开发案例-android跨设备调用方法 项目须要涉及AllJoyn开源物联网框架.前面主要了解了一些AllJoyn主要的概念.像总线,总线附件,总线对象,总线接口这种概念 ...

  4. CSharp程序员学Android开发---3.Android内部元素不填充BUG

    最近公司组织项目组成员开发一个Android项目的Demo,之前没有人有Andoid方面的开发经验,都是开发C#的. 虽说项目要求并不是很高,但是对于没有这方面经验的人来说,第一步是最困难的. 项目历 ...

  5. Android开发环境搭建时遇到问题的解决方法

    版权声明:本文为博主原创文章.未经博主同意不得转载. https://blog.csdn.net/linux_loajie/article/details/33823637 Android开发环境搭建 ...

  6. Android 开发笔记___SD卡文件操作

    package com.example.alimjan.hello_world.Utils; import android.graphics.Bitmap; import android.graphi ...

  7. Android开发 |常见的内存泄漏问题及解决办法

    在Android开发中,内存泄漏是比较常见的问题,有过一些Android编程经历的童鞋应该都遇到过,但为什么会出现内存泄漏呢?内存泄漏又有什么影响呢? 在Android程序开发中,当一个对象已经不需要 ...

  8. Google主推-Android开发利器——Android Studio,这可能是最全的AS教程!

    Android Studio使用手册 "工欲善其事必先利其器" 作为一个Android开发人员来说,一款好的开发工具也是相当重要的,在相当长的时间礼,Google都是基于Eclip ...

  9. Android开发工具Android Studio、Android SDK和Genymotion完全配置

    所谓“工欲善其事,必先利其器”.Android Studio 是谷歌推出一个Android集成开发工具,基于IntelliJ IDEA. 类似 Eclipse ADT,Android Studio 提 ...

随机推荐

  1. js 什么是深拷贝问题?

    一.什么是值类型? 二.什么是引用类型? 三.使用ES Next新特性带来的 Object.assign 方法 和 扩展运算符: 四.Object.assign 方法 和 扩展运算符的 “深入浅出” ...

  2. 如何在open xml excel 中存储自定义xml数据?

    如何在open xml excel 中存储自定义xml数据? 而且不能放在隐藏的cell单元格内,也不能放在隐藏的sheet内,要类似web网站的Application变量,但还不能是VBA和宏之类的 ...

  3. Python 爬虫实例(12)—— python selenium 爬虫

    # coding:utf- from common.contest import * def spider(): url = "http://www.salamoyua.com/es/sub ...

  4. Vue的计算属性和侦听器

    1 计算属性:他是根据对象已有的属性计算出新的属性值.具有缓存的功能,如果原始属性不变,则用缓存.否则,重新计算. 前端 <form> <label>姓</label&g ...

  5. cent os 6.5+ambari+HDP集群安装

    1. 搭建一个测试集群,集群有4台机器,配置集群中每一台机器的/etc/hosts文件: [root@nn .ssh]# cat /etc/hosts 127.0.0.1 localhost loca ...

  6. 分享十:php中并发读写文件冲突的解决方案

    对于日IP不高或者说并发数不是很大的应用,一般不用考虑这些!用一般的文件操作方法完全没有问题.但如果并发高,在我们对文件进行读写操作时,很有可能多个进程对进一文件进行操作,如果这时不对文件的访问进行相 ...

  7. vim常忘命令

    1.复制指定行到当前光标的下一行. #假设当前光标在10行,想把第5行复制到第11行 :5copy. #copy命令有2种简写'co'和't',所以也可以写成下面的格式 :5co. :5t. 参考:h ...

  8. js获取checkbox复选框获取选中的选项

    js获取checkbox复选框获取选中的选项 分享下javascript获取checkbox 复选框获取选中的选项的方法. 有关javascript 获取checkbox复选框的实例数不胜数.js实现 ...

  9. 认识和使用Task

    对于多线程,我们经常使用的是Thread.在我们了解Task之前,如果我们要使用多核的功能可能就会自己来开线程,然而这种线程模型在.net 4.0之后被一种称为基于“任务的编程模型”所冲击,因为tas ...

  10. 【Unity】4.4 添加角色控制器

    分类:Unity.C#.VS2015 创建日期:2016-04-10 一.简介 设计完毕基本的场景后,一般都需要先运行看看效果如何,即先让场景"动起来",以方便观察不同的位置,而不 ...