Android Development (37) android uses android_serialport_api to operate the serial port to solve the permission problem. androidserialport

Source: Internet
Author: User

Android Development (37) android uses android_serialport_api to operate the serial port to solve the permission problem. androidserialport

Recently, we have a project where we want to use the android device to operate the serial port zebra GK888T printer and print the QR code using the printer.

 

Hardware Device connection method:

Android devices connect to the serial port of the zebra printer through serial port RS232

 

Solve the problem of using Android devices to operate the serial port. I found a framework: android_serialport_api, which is hosted in:

Https://code.google.com/p/android-serialport-api/ Google code library, helpless domestic can not download

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

After the download, read the source code and prepare for use.

 

1. copy the files in the jni folder to your project. These are the configuration files called by jni, including:

Android. mk

Application. mk

Gen_SerialPort_h.sh

SerialPort. c

SerialPort. h

2. Copy files under libs to your project. These are native libraries, including

Armeabi/libserial_port.so

Armeabi-v7a/libserial_port.so

X86/libserial_port.so

3. Create a package in your project: android_serialport_api. Copy the class under src 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, the jni library cannot be found.

4. Copy resource files:

Content 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>

5. Modify AndroidManifest. xml and 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 android port "ttyS2". The following is a demonstration:

<?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 before t in compliance with the License. * You may be 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. oneditexceptionlistener; import listener; public class ConsoleActivity extends SerialPortActivity {Button btnSend; EditText minjection; EditText mEmission; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. console); // setTitle ("Loopback test"); mexception = (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 () ;}}); // sends the command to the zebra printer mEmission. setText ("^ XA ^ A0N, 40, 30 ^ FO50, 150 ^ fdhello world ^ FS ^ XZ ");
/* QR code instructions

^ 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 before t in compliance with the License. * You may be 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. get String ("DEVICE", ""); // String path = "ttyS2"; String path = "/dev/ttyS2"; // specify the port // int baudrate = Integer. decode (sp. getString ("BAUDRATE", "-1"); int baudrate = 9600; // specify the rate/* 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;} publ Ic void closeSerialPort () {if (mSerialPort! = Null) {mSerialPort. close (); mSerialPort = null ;}}}

 

 

Finally, do not forget a permission issue. If many devices directly operate on the serial port, the system will prompt that they do not have the permission to read/write. The java layer is required to escalate the permission. The method is as follows:

Run the following command: 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 solution: Open cmd, enter adb shell, and run chmod 777/dev/ttyS2.

 

 

Refer:

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


How to add android Serial Port permissions?

I set up an ADB debugging environment in Win7. Enter "adb shell" in the command line to go to The OK6410A Development Board shell, and enter "vi forlinx. rc". The contents shown in detail are displayed.

Android serial port sub-communication problem, beginner

Does your serial port refer to RS232 port? For RS232, you must first check whether the serial chip is soldered on the board, and then create a serial cable accordingly.
In addition, if you only want to view the system content, you can use ADB.

Related Article

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.