23
23
import java .io .IOException ;
24
24
import java .io .InputStream ;
25
25
import java .io .OutputStream ;
26
+ import java .io .OutputStreamWriter ;
26
27
27
28
public class SerialPort {
28
29
private static final String TAG = "SerialPort" ;
@@ -34,30 +35,51 @@ public class SerialPort {
34
35
private FileOutputStream mFileOutputStream ;
35
36
36
37
public SerialPort (File device , int baudrate , int flags ) throws SecurityException , IOException {
37
- /** Check access permission */
38
+ // 检查权限
38
39
if (!device .canRead () || !device .canWrite ()) {
39
- try {
40
- /** Missing read/write permission, trying to chmod the file */
41
- Process su = Runtime .getRuntime ().exec ("/system/bin/su" );
42
- String cmd = "chmod 777 " + device .getAbsolutePath () + "\n "
43
- + "exit\n " ;
44
- su .getOutputStream ().write (cmd .getBytes ());
45
- if ((su .waitFor () != 0 ) || !device .canRead ()
46
- || !device .canWrite ()) {
47
- throw new SecurityException ();
40
+ // 常见 su 路径
41
+ String [] suPaths = {
42
+ "/system/bin/su" ,
43
+ "/system/xbin/su" ,
44
+ "/sbin/su" ,
45
+ "/vendor/bin/su"
46
+ };
47
+
48
+ boolean chmodSuccess = false ;
49
+ for (String suPath : suPaths ) {
50
+ File suFile = new File (suPath );
51
+ if (suFile .exists () && suFile .canExecute ()) {
52
+ try {
53
+ Process su = Runtime .getRuntime ().exec (suPath );
54
+ OutputStream os = su .getOutputStream ();
55
+ OutputStreamWriter writer = new OutputStreamWriter (os );
56
+ String cmd = "chmod 777 " + device .getAbsolutePath () + "\n exit\n " ;
57
+ writer .write (cmd );
58
+ writer .flush ();
59
+ writer .close ();
60
+ os .close ();
61
+
62
+ if (su .waitFor () == 0 && device .canRead () && device .canWrite ()) {
63
+ chmodSuccess = true ;
64
+ break ;
65
+ }
66
+ } catch (Exception e ) {
67
+ e .printStackTrace ();
68
+ }
48
69
}
49
- } catch (Exception e ) {
50
- e .printStackTrace ();
51
- throw new SecurityException ("execute command /system/bin/su chmod 777 xx Abnormal,Please check whether the serial port grants permission" );
70
+ }
71
+
72
+ if (!chmodSuccess ) {
73
+ throw new SecurityException ("无法修改串口权限,请确保设备已 root 且 su 权限可用" );
52
74
}
53
75
}
54
76
77
+ // 打开串口
55
78
mFd = open (device .getAbsolutePath (), baudrate , flags );
56
- KLog .d (TAG , "SerialPort:open success " );
57
79
if (mFd == null ) {
58
- KLog .e (TAG , "native open returns null" );
59
- throw new IOException ();
80
+ throw new IOException ("native open returns null" );
60
81
}
82
+
61
83
mFileInputStream = new FileInputStream (mFd );
62
84
mFileOutputStream = new FileOutputStream (mFd );
63
85
}
0 commit comments