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

最近有个项目,要使用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

时间: 2024-08-03 19:26:15

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

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

使用 sqlite3 工具操作数据库的两种方式 请尊重他人的劳动成果,转载请注明出处:Android开发之使用sqlite3工具操作数据库的两种方式 http://blog.csdn.net/fengyuzhengfan/article/details/40193123 在Android SDK的tools目录下提供了一"sqlite3.exe工具,它是一个简单的SQLite数据库管理工具,类似于MySQL提供的命令行窗口在有些时候,开发者利用该工具来査询. 管理数据库. 下面介绍两种方式: 第

Android开发工具包 Android SDK

Android SDK 是 Android 的开发工具包. Android开发专区 Android是谷歌(Google)公司推出的手机开发平台. 与iPhone相似,Android采用WebKit浏览器引擎,具备触摸屏.高级图形显示和上网功能,用户能够在手机上查看电子邮件.搜索网址和观看视频节目等,比iPhone等其他手机更强调搜索功能,界面更强大,菜鸟教程QKXue.NET认为Android开发工具包 Android SDK是一种融入全部Web应用的单一平台,下图是 Android 手机平台开

Android开发学习---android下的数据持久化,保存数据到rom文件,android_data目录下文件访问的权限控制

一.需求 做一个类似QQ登录似的app,将数据写到ROM文件里,并对数据进行回显. 二.截图 登录界面: 文件浏览器,查看文件的保存路径:/data/data/com.amos.datasave/files/LoginTest.txt------/data/data/(包名)/files/(文件名) 导出的文件内容: 三.实现代码 新建一个Android 工程.这里我选择的是2.1即API 7,进行开发的,其它都是默认下一步下一步即可. /datasave/res/layout/activity

Android 开发环境 Android Studio

Android Studio 是一个全新的 Android 开发环境,基于 IntelliJ IDEA. 类似 Eclipse ADT,Android Studio 提供了集成的 Android 开发工具用于开发和调试,在 IDEA 的基础上,Android Studio 提供: 基于 Gradle 的构建支持Android 专属的重构和快速修复提示工具以捕获性能.可用性.版本兼容性等问题支持 ProGuard 和应用签名基于模板的向导来生成常用的 Android 应用设计和组件功能强大的布局编

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

最近公司组织项目组成员开发一个Android项目的Demo,之前没有人有Andoid方面的开发经验,都是开发C#的. 虽说项目要求并不是很高,但是对于没有这方面经验的人来说,第一步是最困难的. 项目历时一个多月,4个人开发,最终行成一个可用的Demo,整体效果还非常不错.这其中借鉴了网上的“仿网易客户端的Demo”还有就是学习<疯狂Android>,收获颇多,这里利用几篇文章做一个项目经验总结,还有就是更多的从C# 程序员的观点来理解Android的一些异同之处. 文章目录: CSharp程序

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

Android开发环境搭建时遇到问题的解决方法 错误1: The connection to adb is down, and a severe error has occured. [2013-08-31 16:11:56 -com.qihoo.subject] You must restart adb and Eclipse. [2013-08-31 16:11:56 - com.qihoo.subject] Please ensure that adb is correctly locat

Android 开发笔记 “android调试遇到ADB server didn&#39;t ACK以及顽固的sjk_daemon进程 ”

资源来源:http://blog.csdn.net/wangdong20/article/details/20839533 做Android调试的时候经常会遇到,程序写好了,准备接上手机调试,可不一会儿出现 相信做过android调试的同学都遇到过这个问题,网上说kill掉跟adb相关的进程,重启Eclipse 可是我在任务管理器上没有看到明显的adb进程,我们如何找到它们呢 首先,打开cmd,使用adb命令检查一下,最好是把adb命令的路径放在系统的path环境变量里, 用adb命令也会方便一

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

Android开发华为手机无法看log日志解决方法 上班的时候,由于开发工具由Eclipse改成Android Studio后,原本的华为手机突然无法查看崩溃日志了,大家都知道,若是无法查看日志要它毛用啊? 刚开始没想过是手机问题,毕竟在Eclipse中是完好了,结果在AS中华为了大量时间查找原因,最后,偶然换个手机发现别的手机正常... 最后百度发现解决方法: 进入拨号界面输入:*#*#2846579#*#* 依次选择[工程菜单 —> 后台设置 —> LOG设置 —> LOG开关]  

android开发(37) 使用android系统的账户中心管理账户

在android的系统设置页,有个“账户”分组,里面有很多的账户,很多app都使用了这个账户系统,比如“谷歌”,“淘宝”,“微信”,“华为”等.这些都是大公司呢,有没有可能我们也使用这个,让我们的软件的名称也出现在这里呢,答应是肯定的.看看效果图:     加上这个,我们的app立马就高大上了,如何做到呢? 实现步骤 1. 继承 AbstractAccountAuthenticator 实现 一个 自己的 账户认证器 2. 继承自 service,实现一个服务,该服务使用上一步的 账户认证器 3