要在Android設備上接收串口數據,可以使用Android提供的SerialPort類或第三方庫來實現串口通信。以下是一個簡單的示例代碼,演示如何在Android設備上接收串口數據:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
public class SerialPort {
private static final String TAG = SerialPort.class.getSimpleName();
private FileDescriptor mFd;
private FileInputStream mFileInputStream;
private FileOutputStream mFileOutputStream;
public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException {
mFd = open(device.getAbsolutePath(), baudrate, flags);
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;
}
private native static FileDescriptor open(String path, int baudrate, int flags);
public native void close();
static {
System.loadLibrary("serial_port");
}
}
public class MainActivity extends AppCompatActivity {
private SerialPort mSerialPort;
private InputStream mInputStream;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.text_view);
try {
mSerialPort = new SerialPort(new File("/dev/ttyUSB0"), 9600, 0);
mInputStream = mSerialPort.getInputStream();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
byte[] buffer = new byte[1024];
int size = mInputStream.read(buffer);
if (size > 0) {
final String data = new String(buffer, 0, size);
runOnUiThread(new Runnable() {
@Override
public void run() {
mTextView.setText(data);
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
} catch (SecurityException | IOException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mSerialPort != null) {
mSerialPort.close();
}
}
}
在上面的示例中,我們創建了一個SerialPort類來處理串口通信,并在MainActivity中實例化該類來接收串口數據。我們在一個單獨的線程中讀取串口數據并在UI線程中更新TextView來顯示接收到的數據。最后,在Activity銷毀時關閉串口連接。請注意,上面的代碼僅供參考,實際項目中需要根據具體需求進行修改和優化。