Android开发(35) 使用android_serialport_api 操作串口斑马打印机

概述

使用android设备操作串口的 斑马GK888T打印机,使用打印机打印二维码。

硬件设备连接方式:

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

串口操作类库 android_serialport_api

使用安卓设备操作串口的问题。 我找到一个框架: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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,567评论 25 707
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,085评论 2 44
  • 怎么办怎么办怎么办
    unicornll阅读 112评论 0 0
  • 今天是父亲节,但因为家里网络故障,无法像平常一样一起床就接收到微信信息,早饭后就开车外出了,所以没意识到今天又...
    钢铁柔情阅读 288评论 1 1
  • 九月末,套餐内还剩下六十二分钟的通话时间,于是就着这个借口给他打电话。打了三遍,才接通。我不知道到底是不是没听见,...
    阿雨的大天地阅读 211评论 0 1