Recently, there is a project to use Android devices to operate the serial port zebra GK888T printer, using the printer to print two-dimensional code.

 

Hardware connection mode:

The Android device connects to the serial port of zebra printer through serial port RS232

 

Then we need to solve the problem of using android devices to operate serial ports. I found a framework: Android_serialport_API, which is hosted in:

Code.google.com/p/android-s… Google code base, but domestic can not download

Github.com/cepr/androi… GITHUB address, this can be downloaded

Once downloaded, read the source code and get ready to use it.

 

1. Copy the files in the JNI folder into your project. These are the setup files for jNI calls.

Android.mk

Application.mk

gen_SerialPort_h.sh

SerialPort.c

SerialPort.h

2. Copy the files under liBS into your project, these are native libraries, including

armeabi/libserial_port.so

armeabi-v7a/libserial_port.so

x86/libserial_port.so

3. Create a new package under your project: android_serialport_API and copy the following SRC classes to this package

Application.java

SerialPort.java

SerialPortActivity.java

SerialPortFinder.java

Note that the package name must be android_serialport_API. Or you may need to modify the corresponding module configuration item under Android.mk. Otherwise, you will be prompted to find the library for the JNI call

4. Copy resource files.

The contents of 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>
Copy the code

5. Modify androidmanifest.xml and specify the corresponding “Android :name” configuration in the application node, as shown in the red text below

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

6. Write the test activity below. My device is connected to the Android device port “ttyS2”. Here’s a demo:

<? The 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>Copy the code
/* * 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(); }}}); // send instructions to the zebra printer mEmission. SetText ("^XA^A0N,40,30^FO50,150^FDHELLO WORLD^FS^XZ"); /*Copy the code

200 ^ ^ XA ^ PMY ^ FO200, BQ, 2, 10 ^ FDD03040C, LA, 012345678912 aabbqrcode ^ 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)); }}}); }}Copy the code

 

/* * 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; / / / * * / if the Check the parameters specified rate ((path. The 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; }}}Copy the code

 

 

Finally, do not forget the problem of operation permissions, many devices directly operate the serial port, will be prompted to read/write problem, need to Java layer to raise the right, the method is as follows:

Execute the instruction using the following method: chmod777 /dev/ttyS2
Copy the code

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(); }}Copy the code

Manual solution: Open CMD, enter ADB shell, and run chmod 777 /dev/ttys2

 

 

Reference:

Code.google.com/p/android-s…

Github.com/cepr/androi…

Blog.csdn.net/imyang2007/…

Blog.csdn.net/imyang2007/…

Bbs.csdn.net/topics/3802…