最近有个项目,要使用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 serialport.</string><string name="error_unknown">The serial port can not be opened for an unknownreason.</string>

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

    <applicationandroid: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" ><EditTextandroid: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><EditTextandroid:id="@+id/EditTextEmission"android:layout_width="fill_parent"android:layout_height="wrap_content"android:hint="Emission"android:lines="4"android:text="" ></EditText><Buttonandroid: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;@Overrideprotected 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() {@Overridepublic 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

    */}@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));}}});}
}

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

转载于:https://www.cnblogs.com/vir56k/p/3981873.html

android开发(37) android使用android_serialport_api 操作串口,解决权限问题相关推荐

  1. 【Android开发】Android入门安装与使用教程——以Android Studio3.6.1为例

    [Android开发]Android入门教程--以Android Studio3.6.1为例 1.为什么要学习Android 2.学习资源 3.安装Android Studio 3.1 下载安装包 3 ...

  2. 写给Android开发的Android简史

    写给Android开发的Android简史

  3. <Android开发> Android vold - 第三篇 vold 的NetLinkManager类简介

    本系列主要介绍 Android vold,分为以下篇章 <Android开发> Android vold - 第一篇 vold前言简介 <Android开发> Android ...

  4. <Android开发> Android vold - 第四篇 vold 的NetlinkHandler类简介

    本系列主要介绍 Android vold,分为以下篇章 <Android开发> Android vold - 第一篇 vold前言简介 <Android开发> Android ...

  5. <Android开发> Android vold - 第七篇 vold 的runCommand()方法解析

    本系列主要介绍 Android vold,分为以下篇章 <Android开发> Android vold - 第一篇 vold前言简介 <Android开发> Android ...

  6. <Android开发> Android vold - 第二篇 vold 的main()函数简介

    本系列主要介绍 Android vold,分为以下篇章 <Android开发> Android vold - 第一篇 vold前言简介 <Android开发> Android ...

  7. 【Android开发】Android Studio中进行简单的WebView构建浏览器开发1

    [Android开发]Android Studio中进行简单的WebView构建浏览器开发 第一步:新建一个Android Project 第二步:修改AndroidMainfest.xml文件 第三 ...

  8. 【Android开发】Android Studio中进行简单的WebView构建浏览器开发2

    [[Android开发]Android Studio中进行简单的WebView构建浏览器开发2 第1步:在上一篇博客的基础上,修改activity_main.xml 第2步:在MainActivity ...

  9. <Android开发> Android vold - 第一篇 vold前言简介

    本系列主要介绍 Android vold,分为以下篇章 <Android开发> Android vold - 第一篇 vold前言简介 <Android开发> Android ...

  10. Android开发 系统服务,android 系统服务 开发

    <Android系统服务开发>分析了安卓提供的硬件控制机制.编写团队目前均从事相关工作,直接对平台源代码及日志进行分析及测试,介绍了目前尚未普及的安卓平台的硬件控制基本原理及实际框架的劋作 ...

最新文章

  1. fileupload控件在ajax中无法使用
  2. 聊聊网易技术如何帮教育行业开出花
  3. Nhibernate配置和访问数据问题
  4. Java 调用EXE
  5. 在python中函数和类都属于可调用对象_在Python中函数和类都属于可调用对象
  6. 基于51单片机的时钟系统
  7. Linux性能测试分析命令_sar
  8. C#设计模式---模板方法模式(Template Method Pattern)
  9. log4j的详细介绍
  10. python调用按键精灵插件_按键精灵 插件命令 重中之重务必要记住怎么操作
  11. NodeJS运行时抛出: Error: listen EADDRINUSE :::3000
  12. c语言----斐波那契数列
  13. String的内置方法、字符号拼接、创建字典、制作购物车、元组
  14. 教你开发一个JS代码加密工具
  15. 什么是超大附件?邮箱的超大附件怎么打开?哪个邮箱发送附件大?
  16. 没有对象,你凭什么成为百万富翁
  17. 微信小程序之自定义表单组件(radio)
  18. 凯翔:可以同时替代Nimble和Nutanix的存储
  19. (2020)Simple Copy-Paste is a Strong Data Augmentation Method for Instance Segmentation
  20. dns劫持是什么意思?常见的劫持有哪些?

热门文章

  1. 数论之勾股数组(毕达哥拉斯三元组)
  2. PhoneGap:免费开源的 HTML5 移动应用开发平台
  3. Understanding Bootstrap Of Oracle Database
  4. OO思想(只留做自己看理解)
  5. M1支持 Accusonus ERA Bundle for mac(音频降噪消除去混音插件包)
  6. 怎么在Mac上重建“聚焦”索引?
  7. id 和 class 选择器
  8. 使用iMazing为iPad添加PDF文档
  9. MongoDB 3.2+ 安全授权登录访问控制
  10. 几个关于oracle 11g ASM的问题