Android Development (Notoginseng) Android uses ANDROID_SERIALPORT_API to operate the serial port to resolve permissions issues

Source: Internet
Author: User

Recently, there is a project to use the Android device to operate the serial port of the Zebra gk888t printer, using the printer to print the two-dimensional code.

How to connect hardware devices:

Android device connects the serial port of the Zebra printer via serial RS232

Then we need to solve: the use of Android devices to operate the serial port problem. I found a framework: ANDROID_SERIALPORT_API, this framework is hosted in:

https://code.google.com/p/android-serialport-api/Google's code base, helpless domestic can not download

Https://github.com/cepr/android-serialport-api GitHub address, this can be downloaded

After downloading, read the source code, ready to use.

1. Copy the files under the Jni folder into your project, these are the settings files for the JNI call, including:

Android.mk

Application.mk

gen_serialport_h.sh

Serialport.c

SerialPort.h

2. Copy the files under Libs to your project, these are the native libraries, including

Armeabi/libserial_port.so

Armeabi-v7a/libserial_port.so

X86/libserial_port.so

3. Create a new PACKAGE:ANDROID_SERIALPORT_API under your project and copy the following SRC class to this package

Application.java

Serialport.java

Serialportactivity.java

Serialportfinder.java

Note that the package name must be ANDROID_SERIALPORT_API. Or you need to modify the corresponding module configuration item under ANDROID.MK. Otherwise, you will be prompted not to find the library for the JNI call

4. Copy the resource files, etc.:

Content of String.xml:

    <string name= "error_configuration" >please Configure your serial port first.</string> do not     There are read/write permission to the serial        port. </string> for an      unknown        reason. </string>

5. Modify Androidmanifest.xml, specify the corresponding "Android:name" configuration on the application node, as shown in the red text below

    <application        android:allowbackup= "true"        android:name= "Android_serialport_api. Application "        android:theme=" @style/apptheme ">

6. Write the test activity below. My device is connected to the port "TtyS2" on the Android device, and here is a demo:

<?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 Cedric priscal * * Licensed under the Apache License, Version 2.0 (the "License"); * you are not us E this file except in compliance with the License. * Obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0* * Unless required by applicable or agreed to writing, software * Distributed under the License is Distribut Ed 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. */ PackageZyf.serialportdemo;Importjava.io.IOException;ImportZYF.SERIALPORTDEMO.R;ImportAndroid.os.Bundle;Importandroid.view.KeyEvent;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView;ImportAndroid.widget.TextView.OnEditorActionListener;ImportAndroid_serialport_api. serialportactivity; Public classConsoleactivityextendsserialportactivity {Button btnsend;    EditText mreception;        EditText memission; @Overrideprotected voidonCreate (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 (NewOnclicklistener () {@Override Public voidOnClick (View v) {String text=Memission.gettext (). toString (); Try{moutputstream.write (NewString (text). GetBytes ()); Moutputstream.write (' \ n '); } Catch(IOException e) {e.printstacktrace ();        }            }        }); Send instructions to Zebra printer Memission.settext ("^xa^a0n,40,30^fo50,150^fdhello World^fs^xz");
/* QR code instruction

^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< /span> new String (buffer, 0

/** Copyright Cedric priscal * * Licensed under the Apache License, Version 2.0 (the "License"); * you are not us E this file except in compliance with the License. * Obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0* * Unless required by applicable or agreed to writing, software * Distributed under the License is Distribut Ed 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. */ PackageAndroid_serialport_api;ImportJava.io.File;Importjava.io.IOException;Importjava.security.InvalidParameterException;Importandroid.content.SharedPreferences; Public classApplicationextendsandroid.app.Application { PublicSerialportfinder Mserialportfinder =NewSerialportfinder (); PrivateSerialPort Mserialport =NULL;  PublicSerialPort Getserialport ()throwsSecurityException, 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";//Specify Port//int baudrate = Integer.decode (sp.getstring ("BaudRate", "1"));            intBaudRate = 9600;//Specified rate            /*Check Parameters*/            if((path.length () = = 0) | | (BaudRate = =-1)) {                Throw Newinvalidparameterexception (); }            /*Open the serial port*/Mserialport=NewSerialPort (NewFile (path), baudrate, 0); }        returnMserialport; }     Public voidCloseserialport () {if(Mserialport! =NULL) {mserialport.close (); Mserialport=NULL; }    }}

Finally do not forget a permission to operate the problem, many devices directly operate the serial port, will prompt the problem of no permission read/write, the Java layer to take the right, the method is as follows:

Execute the instruction using the following method: 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 (); } }

Manual workaround: Open cmd, enter adb shell, execute: chmod 777/dev/ttys2

 

Reference:

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 Development (Notoginseng) Android uses ANDROID_SERIALPORT_API to operate the serial port to resolve permissions issues

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.