導航:首頁 > 操作系統 > androidjava串口

androidjava串口

發布時間:2022-10-29 07:44:53

⑴ 求助,求大神,android與串口通信

轉載最近做的項目用到了藍牙串口通訊功能.畢竟是接觸到底層的一些東西,讓吾等局限於java編程思想的小菜遇到了一些意想不到的問題.

問題一,連接不上藍牙串口
直接在android自帶的藍牙例子上嘗試,發現根本連接不上藍牙串口,後來對比別人的代碼發現uuid不一樣.因為以前用過UUID.randomUUID();所以想當然的認為所有uuid都是隨機生成的.通過搜索發現,android連接藍牙串口的話,必須要這個UUID

UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

問題二,在讀取從藍牙串口返回的數據時,一直阻塞在inpustream.read(buffer);那裡.

起初是因為仿照網上的例子,直接發送指令的16進制字元串過去,返回不到數據.後來通過反編譯可以使用的藍牙串口助手apk發現,需要發送的不是16進制字元串的byte數組.而是將16進制字元串轉換成的byte數組.

String string = "01 00 05 07 00 00 00 00";
string = string.replaceAll(" ", ""); byte[] bytes = hexString2Bytes(string);//正確,要發送這個bytes
byte[] bytes = string.getBytes();//錯誤,發送這個bytes獲取不到數據.

附上hexString2Bytes方法

/**
* Convert hex string to byte[] 把為字元串轉化為位元組數組
*
* @param hexString
* the hex string
* @return byte[]
*/
public static byte[] hexStringToBytes(String hexString) {
hexString = hexString.replaceAll(" ", "");
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase(Locale.getDefault());
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}

/**
* Convert char to byte
*
* @param c
* char
* @return byte
*/
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}

得出結論.串口通訊時,如果獲取到錯誤的信息,是不返回數據的.在socket連接時.如果沒有獲取到數據.inputstream.read(buffer);是會一直阻塞的.

⑵ 誰有沒有Android串口的使用例子

1 首先做的是創建新的工程然後添加一下文件


3代碼

好了 然後就是關於這個頁面的Code了,

這是我的:

package android.serialport;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.BreakIterator;
import java.util.ServiceConfigurationError;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MyserialActivity extendsActivity
{
EditText sendedit;
EditText receiveedit;
FileInputStream mInStream;
FileOutputStream mOutStream;
SerialPort classserialport;
ReadThread mReadThread;

private class ReadThread extends Thread
{
public void run()
{
super.run();
while(!isInterrupted())
{
int size;
}
}
}


void onDataReceive(final byte[] buffer,finalint size)
{
runOnUiThread(new Runnable()
{

@Override
publicvoid run()
{
// TODO Auto-generated method stub
if(mReadThread != null)
{
receiveedit.append(newString(buffer,0,size));
}
}
});
}
@Override
protectedvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_myserial);

sendedit= (EditText)findViewById(R.id.editText1);
receiveedit=(EditText)findViewById(R.id.editText2);


receiveedit.setFocusable(false);//進制輸入
/*
* 打開串口
* */
finalButton openserial =(Button)findViewById(R.id.button1);
openserial.setOnClickListener(newView.OnClickListener()
{

@Override
publicvoid onClick(View arg0)
{
//TODO Auto-generated method stub
try
{
classserialport=new SerialPort(new File("/dev/ttyS2"),9600);
}catch(SecurityExceptione)
{
e.printStackTrace();
}
catch(IOExceptione)
{
e.printStackTrace();
}
mInStream=(FileInputStream) classserialport.getInputStream();
Toast.makeText(MyserialActivity.this,"串口打開成功",Toast.LENGTH_SHORT).show();
}
});
/*
* 發送數據
* */
finalButton sendButton =(Button)findViewById(R.id.button2);
sendButton.setOnClickListener(newView.OnClickListener()
{

@Override
publicvoid onClick(View arg0)
{

Stringindata;
indata=sendedit.getText().toString();
//TODO Auto-generated method stub
try
{
mOutStream=(FileOutputStream) classserialport.getOutputStream();
mOutStream.write(indata.getBytes());
mOutStream.write(' ');
}
catch(IOExceptione)
{
e.printStackTrace();
}
Toast.makeText(MyserialActivity.this,"數據發送成功",Toast.LENGTH_SHORT).show();
sendedit.setText("");
}
});
/*
* 接收數據
* */
finalButton receButton= (Button)findViewById(R.id.button3);
receButton.setOnClickListener(newView.OnClickListener()
{//inttag =0;

@Override
publicvoid onClick(View arg0)
{
// TODO Auto-generated method stub
intsize;
try
{
byte[]buffer = new byte[64];
if(mInStream== null) return;
size= mInStream.read(buffer);
if(size>0)
{
receiveedit.setText("");

}
if(size>0)
{
onDataReceive(buffer,size);
}
inttag =1;

receiveedit.setText(newString(buffer, 0, size));

}catch(IOExceptione)
{
e.printStackTrace();
return;
}
}

privateboolean isInterrupted()
{
// TODO Auto-generated methodstub
returnfalse;
}
});
/*
* 清楚接收區
* */
finalButton ClearButton = (Button)findViewById(R.id.clear);
ClearButton.setOnClickListener(newView.OnClickListener()
{

@Override
publicvoid onClick(View arg0)
{
//TODO Auto-generated method stub
receiveedit.setText("");
}
});}

@Override
publicboolean onCreateOptionsMenu(Menu menu)
{
//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.myserial,menu);
returntrue;
}

}

好吧 你做好了。

3需要載入的文件

下面我把所需要添加的代碼貼一貼

第一個是Serialport.java

/*
* 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 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;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.util.Log;

public class SerialPort {

private static final String TAG = "SerialPort";

/*
* Do not remove or rename the field mFd: it is used by native method close();
*/
private FileDescriptor mFd; //創建一個文件描述符對象 mFd
private FileInputStream mFileInputStream;
private FileOutputStream mFileOutputStream;

public SerialPort(File device, int baudrate) throws SecurityException, IOException {
/*
* 檢查訪問許可權
* */
/* Check access permission */
if (!device.canRead() || !device.canWrite()) {//如果設備不可讀或者設備不可寫
try {
/* Missing read/write permission, trying to chmod the file *///沒有讀寫許可權,就嘗試去掛載許可權
Process su; //流程進程 su
su = Runtime.getRuntime().exec("/system/bin/su");//通過執行掛載到/system/bin/su 獲得執行
String cmd = "chmod 777 " + device.getAbsolutePath() + " "
+ "exit ";
/*String cmd = "chmod 777 /dev/s3c_serial0" + " "
+ "exit ";*/
su.getOutputStream().write(cmd.getBytes());//進程。獲得輸出流。寫(命令。獲得二進制)
if ((su.waitFor() != 0) || !device.canRead()
|| !device.canWrite()) {//如果 進程等待不是0 或者 設備不能讀寫就
throw new SecurityException();//拋出一個許可權異常
}
} catch (Exception e) {
e.printStackTrace();
throw new SecurityException();
}
}
/*
*
* */
mFd = open(device.getAbsolutePath(), baudrate);
//device.getAbsolutePath()這是要掛載的路徑new File("/dev/ttyS2")
if (mFd == null) {
Log.e(TAG, "native open returns null");
throw new IOException();//輸入輸出異常
}
//將文件描述符 做輸入輸出流的參數 傳遞給創建的輸入輸出流
mFileInputStream = new FileInputStream(mFd);
mFileOutputStream = new FileOutputStream(mFd);
}

// Getters and setters
public InputStream getInputStream() {
return mFileInputStream;
}

public OutputStream getOutputStream() {
return mFileOutputStream;
}

// JNI
private native static FileDescriptor open(String path, int baudrate);
public native void close();
static {
System.loadLibrary("serial_port");
}
}

第二個是SerialPortFinder.java

/*
* 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 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;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Iterator;
import java.util.Vector;

import android.util.Log;

public class SerialPortFinder {

/*
* 創建一個驅動程序類
* */
public class Driver {
public Driver(String name, String root) {
mDriverName = name;//String 類型的
mDeviceRoot = root;
}
private String mDriverName;
private String mDeviceRoot;
Vector<File> mDevices = null;
/*
* Vector 類在 java 中可以實現自動增長的對象數組
* 簡單的使用方法如下:
vector<int> test;//建立一個vector
test.push_back(1);
test.push_back(2);//把1和2壓入vector這樣test[0]就是1,test[1]就是2
* */
public Vector<File> getDevices() {
if (mDevices == null) {
mDevices = new Vector<File>();
File dev = new File("/dev");
File[] files = dev.listFiles();
int i;
for (i=0; i<files.length; i++) {
if (files[i].getAbsolutePath().startsWith(mDeviceRoot)) {
Log.d(TAG, "Found new device: " + files[i]);
mDevices.add(files[i]);
}
}
}
return mDevices;
}

public String getName() {
return mDriverName;
}
}
/*
*
*
* */
private static final String TAG = "SerialPort";

private Vector<Driver> mDrivers = null;

Vector<Driver> getDrivers() throws IOException {
if (mDrivers == null) {
mDrivers = new Vector<Driver>();
LineNumberReader r = new LineNumberReader(new FileReader("/proc/tty/drivers"));
String l;
while((l = r.readLine()) != null) {
String[] w = l.split(" +");
if ((w.length == 5) && (w[4].equals("serial"))) {
Log.d(TAG, "Found new driver: " + w[1]);
mDrivers.add(new Driver(w[0], w[1]));
}
}
r.close();
}
return mDrivers;
}

public String[] getAllDevices() {
Vector<String> devices = new Vector<String>();
// Parse each driver
Iterator<Driver> itdriv;
try {
itdriv = getDrivers().iterator();
while(itdriv.hasNext()) {
Driver driver = itdriv.next();
Iterator<File> itdev = driver.getDevices().iterator();
while(itdev.hasNext()) {
String device = itdev.next().getName();
String value = String.format("%s (%s)", device, driver.getName());
devices.add(value);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return devices.toArray(new String[devices.size()]);
}

public String[] getAllDevicesPath() {
Vector<String> devices = new Vector<String>();
// Parse each driver
Iterator<Driver> itdriv;
try {
itdriv = getDrivers().iterator();
while(itdriv.hasNext()) {
Driver driver = itdriv.next();
Iterator<File> itdev = driver.getDevices().iterator();
while(itdev.hasNext()) {
String device = itdev.next().getAbsolutePath();
devices.add(device);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return devices.toArray(new String[devices.size()]);
}
}

第三個是Android.mk

#
# 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 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.
#

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

TARGET_PLATFORM := android-3
LOCAL_MODULE := serial_port
LOCAL_SRC_FILES := SerialPort.c
LOCAL_LDLIBS := -llog

include $(BUILD_SHARED_LIBRARY)

第四個是SerialPort.c

/*
* 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 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.
*/

#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <jni.h>

#include "android/log.h"
static const char *TAG="serial_port";
#define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO, TAG, fmt, ##args)
#define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, TAG, fmt, ##args)
#define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, TAG, fmt, ##args)

static speed_t getBaudrate(jint baudrate)
{
switch(baudrate) {
case 0: return B0;
case 50: return B50;
case 75: return B75;
case 110: return B110;
case 134: return B134;
case 150: return B150;
case 200: return B200;
case 300: return B300;
case 600: return B600;
case 1200: return B1200;
case 1800: return B1800;
case 2400: return B2400;
case 4800: return B4800;
case 9600: return B9600;
case 19200: return B19200;
case 38400: return B38400;
case 57600: return B57600;
case 115200: return B115200;
case 230400: return B230400;
case 460800: return B460800;
case 500000: return B500000;
case 576000: return B576000;
case 921600: return B921600;
case 1000000: return B1000000;
case 1152000: return B1152000;
case 1500000: return B1500000;
case 2000000: return B2000000;
case 2500000: return B2500000;
case 3000000: return B3000000;
case 3500000: return B3500000;
case 4000000: return B4000000;
default: return -1;
}
}

/*
* Class: cedric_serial_SerialPort
* Method: open
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT jobject JNICALL Java_android_serialport_SerialPort_open
(JNIEnv *env, jobject thiz, jstring path, jint baudrate)
{
int fd;
speed_t speed;
jobject mFileDescriptor;

/* Check arguments */
{
speed = getBaudrate(baudrate);
if (speed == -1) {
/* TODO: throw an exception */
LOGE("Invalid baudrate");
return NULL;
}
}

/* Opening device */
{
jboolean is;
const char *path_utf = (*env)->GetStringUTFChars(env, path, &is);
LOGD("Opening serial port %s", path_utf);
fd = open(path_utf, O_RDWR | O_DIRECT | O_SYNC);
LOGD("open() fd = %d", fd);
(*env)->ReleaseStringUTFChars(env, path, path_utf);
if (fd == -1)
{
/* Throw an exception */
LOGE("Cannot open port");
/* TODO: throw an exception */
return NULL;
}
}

/* Configure device */
{
struct termios cfg;
LOGD("Configuring serial port");
if (tcgetattr(fd, &cfg))
{
LOGE("tcgetattr() failed");
close(fd);
/* TODO: throw an exception */
return NULL;
}

cfmakeraw(&cfg);
cfsetispeed(&cfg, speed);
cfsetospeed(&cfg, speed);

if (tcsetattr(fd, TCSANOW, &cfg))
{
LOGE("tcsetattr() failed");
close(fd);
/* TODO: throw an exception */
return NULL;
}
}

/* Create a corresponding file descriptor */
{
jclass cFileDescriptor = (*env)->FindClass(env, "java/io/FileDescriptor");
jmethodID iFileDescriptor = (*env)->GetMethodID(env, cFileDescriptor, "<init>", "()V");
jfieldID descriptorID = (*env)->GetFieldID(env, cFileDescriptor, "descriptor", "I");
mFileDescriptor = (*env)->NewObject(env, cFileDescriptor, iFileDescriptor);
(*env)->SetIntField(env, mFileDescriptor, descriptorID, (jint)fd);
}

return mFileDescriptor;
}

/*
* Class: cedric_serial_SerialPort
* Method: close
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_android_serialport_SerialPort_close
(JNIEnv *env, jobject thiz)
{
jclass SerialPortClass = (*env)->GetObjectClass(env, thiz);
jclass FileDescriptorClass = (*env)->FindClass(env, "java/io/FileDescriptor");

jfieldID mFdID = (*env)->GetFieldID(env, SerialPortClass, "mFd", "Ljava/io/FileDescriptor;");
jfieldID descriptorID = (*env)->GetFieldID(env, FileDescriptorClass, "descriptor", "I");

jobject mFd = (*env)->GetObjectField(env, thiz, mFdID);
jint descriptor = (*env)->GetIntField(env, mFd, descriptorID);

LOGD("close(fd = %d)", descriptor);
close(descriptor);
}

⑶ android 串口通信丟失數據原因

我現在測試也遇到這個問題,我是根據android_serialport_api裡面的代碼做的,就是在android端接收串口發過來的數據不完整,幾乎每次都只是接收一部分的數據,另外一部分就不知道跑到哪裡去,請問你這個問題你解決了嗎

⑷ android如何讀取串口數據

代碼如下:
import com.friendlyarm.AndroidSDK.HardwareControler;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

public class MapGuider_Activity extends Activity{

private int serial_fd=0;
private byte[] serial_RevBuf=new byte[100];
private byte[] serial_SendBuf="fsjajd".getBytes();
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mapguider);
serial_fd=HardwareControler.openSerialPort("/dev/s3c2410_serial1", 115200, 8, 1);
if(serial_fd!=-1)
{
System.out.println("打開串口成功");
HardwareControler.write(serial_fd, serial_SendBuf);
lac_handler.post(RevicePosDataThread);
}
else
{
System.out.println("指定的串口不存在或在其它進程中已被打開");
}
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
HardwareControler.close(serial_fd);
System.out.println("關閉串口");
lac_handler.removeCallbacks(RevicePosDataThread);
super.onDestroy();
}

Handler lac_handler =new Handler(){

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
}

};
Runnable RevicePosDataThread =new Runnable()
{
int err=0;
String s;
public void run() {
// TODO Auto-generated method stub
while(true)
{
//Looper.prepare();
err=HardwareControler.select(serial_fd, 1, 0);
if(err==1)//有數據可讀
{
HardwareControler.read(serial_fd, serial_RevBuf, 10);
s=new String(serial_RevBuf);
System.out.println("接收到串口數據"+s);
}
else if(err==0) //無數據可讀
{
System.out.println("沒有接收到串口數據");
}
else //出錯
{
System.out.println("接收到串口數據出錯");
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

};

}

⑸ Android平台到底能不能通過串口發送AT指令呢,急!!!

AT命令(Attention)在手機中,用於對modem(也就是移動模塊)通過串口命令進行操作,處理與語音電話、簡訊和數據。

關於AT命令:

  1. Android系統與AT命令

    對於智能手機,AP和BP分離的情況,在AP上的系統通過串口和BP通信是個不錯方式。在Android的源碼中有一個內部包com.android.internal.telephony中有對AT命令的封裝和解析,但這種internal的包開發者不能調用的SDK部分,可以用來封裝ROM。這說明Android對AT command的方式是支持的。

  2. 對於Android如何調用AT command

    用root登錄命令行,直接對串口進行操作,如echo -e "AT " > /dev/smd0

    具體的串口,不同設備會有不同,甚至不一定會提供。這種方式,開發者是可以調用的,通過Runtime.exec直接執行命令行命令,但要求是root,例如echo -e "ATD123456789; " > /dev/smd0,撥打123456789的號碼。

  3. 目前最新的AT命令標准發布與2014.6.27,似乎還活得挺滋潤的。但是給出的keywords是UMTS, GSM, command, terminal, LTE這說明CDMA確實很可能不是採用AT命令的方式。

⑹ java串口,讀取和發送數據

publicstaticvoidprocess(){
try{
EnumerationportList=CommPortIdentifier.getPortIdentifiers();
while(portList.hasMoreElements())
{
CommPortIdentifierportId=(CommPortIdentifier)portList.nextElement();
if(portId.getPortType()==CommPortIdentifier.PORT_SERIAL)//如果埠類型是串口則判斷名稱
{
if(portId.getName().equals("COM1")){//如果是COM1埠則退出循環
break;
}else{
portId=null;
}
}
}
SerialPortserialPort=(SerialPort)portId.open("Serial_Communication",1000);//打開串口的超時時間為1000ms
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);//設置串口速率為9600,數據位8位,停止位1們,奇偶校驗無
InputStreamin=serialPort.getInputStream();//得到輸入流
OutputStreamout=serialPort.getOutputStream();//得到輸出流

//進行輸入輸出操作
//操作結束後
in.close();
out.close();
serialPort.close();//關閉串口

}catch(PortInUseExceptione){
e.printStackTrace();
}catch(){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}

}

⑺ android串口許可權怎麼加

1.在init.rc中提權 chmod 777 /dev/ttyUSB0
2.在device.c中提許可權,這個比較隱蔽,不易發現,詳細可以參考我的blog:http://blog.csdn.net/yiyaaixuexi/article/details/6803593
3.每次都在java層去提權,cmd為提權命令

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

⑻ android串口消息

android串口消息連接的方法為:
1.模擬器可以使用PC的串口。
啟動模擬器並載入PC串口 命令如下。
運行 emulator @模擬器名稱 -qmu -serial COM1。
2.查看串口是否被載入。
啟動後使用 adb shell 命令打開命令行
cd dev 查看會發現ttyS0 ttyS1 ttyS2,其他ttyS2 就是我們載入上來的串口COM1
3.修改許可權
chmod 777 ttyS2
現在我們可以開發串口程序了。
4.串口程序實例
下載libserial_port.so ,放入libs/armeabi 目錄,可以自己創建此目錄
libserial_port.so 下載地址:
http://code.google.com/p/android-serialport-api/
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.util.Log;

public class SerialPort {

private static final String TAG = "SerialPort";

private FileDescriptor mFd;
private FileInputStream mFileInputStream;
private FileOutputStream mFileOutputStream;

public SerialPort(File device, int baudrate) throws SecurityException, IOException {

if (!device.canRead() || !device.canWrite()) {
try {
Process su;
su = Runtime.getRuntime().exec("/system/bin/su");
String cmd = "chmod 666 " + device.getAbsolutePath() + "n"
+ "exitn";
su.getOutputStream().write(cmd.getBytes());
if ((su.waitFor() != 0) || !device.canRead()
|| !device.canWrite()) {
throw new SecurityException();
}
} catch (Exception e) {
e.printStackTrace();
throw new SecurityException();
}
}

mFd = open(device.getAbsolutePath(), baudrate);
if (mFd == null) {
Log.e(TAG, "native open returns null");
throw new IOException();
}
mFileInputStream = new FileInputStream(mFd);
mFileOutputStream = new FileOutputStream(mFd);
}

public InputStream getInputStream() {
return mFileInputStream;
}

public OutputStream getOutputStream() {
return mFileOutputStream;
}

//JNI
private native static FileDescriptor open(String path, int baudrate);
public native void close();
static {
System.loadLibrary("serial_port");
}
}

####################################

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class PrintClass {

//輸入流
private static InputStream in;
//輸出流
private static OutputStream out;

private static final String PORT = "/dev/ttyS2";//串口

private SerialPort serialPort;

private void Connect()
{
try {
serialPort = new SerialPort(new File(PORT), 38400);

in = serialPort.getInputStream();
out = serialPort.getOutputStream();

} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public void CloseSerialPort()
{
try {
out.close();
in.close();
serialPort.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

⑼ Java怎麼讀取串口數據

public static void process() {
try {
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements())
{
CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)//如果埠類型是串口則判斷名稱
{
if(portId.getName().equals("COM1")){//如果是COM1埠則退出循環
break;
}else{
portId=null;
}
}
}
SerialPort serialPort = (SerialPort)portId.open("Serial_Communication", 1000);//打開串口的超時時間為1000ms
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);//設置串口速率為9600,數據位8位,停止位1們,奇偶校驗無
InputStream in = serialPort.getInputStream();//得到輸入流
OutputStream out = serialPort.getOutputStream();//得到輸出流

//進行輸入輸出操作
//操作結束後
in.close();
out.close();
serialPort.close();//關閉串口

} catch (PortInUseException e) {
e.printStackTrace();
} catch ( e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

⑽ android中怎麼打開串口功能

1/yiyaaixuexi/article/details/6803593 3.每次都在java層去提權,cmd為提權命令 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(); } }

閱讀全文

與androidjava串口相關的資料

熱點內容
只能用命令獲得的四種方塊 瀏覽:358
怎麼用命令方塊防止開創造 瀏覽:807
掃描版的pdf 瀏覽:790
編程貓怎樣做3d游戲 瀏覽:207
怎麼查找雲伺服器上的ftp 瀏覽:156
我的世界伺服器如何注冊賬號 瀏覽:934
統計英文字元python 瀏覽:423
linux信息安全 瀏覽:908
壓縮機接線柱爆 瀏覽:999
程序員自主創業 瀏覽:584
匯編程序員待遇 瀏覽:359
怎麼批量有順序的命名文件夾 瀏覽:211
杭州程序員健身 瀏覽:19
dvd光碟存儲漢子演算法 瀏覽:758
蘋果郵件無法連接伺服器地址 瀏覽:963
phpffmpeg轉碼 瀏覽:672
長沙好玩的解壓項目 瀏覽:145
專屬學情分析報告是什麼app 瀏覽:564
php工程部署 瀏覽:833
android全屏透明 瀏覽:737