前幾天有需要在java代碼中調用二進制程序,就在網上找了些資料,寫點東西記錄下。
Android 也是基於linux 的系統,當然也可以運行二進制的可執行文件。只不過Android 限制了直接的方式只能安裝運行apk文件。雖然有NDK可以用動態鏈接庫的方式來用C的二進制代碼,但畢竟不方便。至少我們可以調用linux的一些基本命令,如ls,rm等。
第一種方法:Runtime.exec(String[] args)
這種方法是java語言本身來提供的,在Android里面也可以使用。args是要執行的參數數組。大概用法如下:
String[] args = new String[2];
args[0] = "ls";
args[1] = "-l";
try
{
Process process = Runtime.getRuntime().exec(arg);
//get the err line
InputStream stderr = process.getErrorStream();
InputStreamReader isrerr = new InputStreamReader(stderr);
BufferedReader brerr = new BufferedReader(isrerr);
//get the output line InputStream outs = process.getInputStream();
InputStreamReader isrout = new InputStreamReader(outs);
BufferedReader brout = new BufferedReader(isrout);
String errline = null;
String result = "";
// get the whole error message string while ( (line = brerr.readLine()) != null)
{
result += line;
result += "/n";
}
if( result != "" )
{
// put the result string on the screen
}
// get the whole standard output string
while ( (line = brout.readLine()) != null)
{
result += line;
result += "/n";
}
if( result != "" )
{
// put the result string on the screen
}
}catch(Throwable t)
{
t.printStackTrace();
}
以上代碼執行了linux的標准命令 ls -l。執行此命令后的標准輸出是在brout中。如果出錯,像參數錯誤,命令錯誤等信息就會放在brerr中。
有需要的話從里面讀出來便可。
第二種方法:Class.forName("android.os.Exec")
代碼大概是這樣:
try {
// android.os.Exec is not included in android.jar so we need to use reflection. Class<?> execClass = Class.forName("android.os.Exec"); Method createSubprocess = execClass.getMethod("createSubprocess", String.class, String.class, String.class, int[].class); Method waitFor = execClass.getMethod("waitFor", int.class); // Executes the command. // NOTE: createSubprocess() is asynchronous. int[] pid = new int[1]; FileDescriptor fd = (FileDescriptor)createSubprocess.invoke( null, "/system/bin/ls", "/sdcard", null, pid); // Reads stdout. // NOTE: You can write to stdin of the command using new FileOutputStream(fd). FileInputStream in = new FileInputStream(fd); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String output = ""; try { String line; while ((line = reader.readLine()) != null) { output += line + "/n"; } } catch (IOException e) { // It seems IOException is thrown when it reaches EOF. } // Waits for the command to finish. waitFor.invoke(null, pid[0]); return output; } catch( ... )
...
這種方法是用了 Android 提供的android.os.Exec類。在 Android 的源代碼中已經提供了類似 terminal 的ap,在
/development/apps/Term/src/com/android/term 中,這個ap就是用android.os.Exec來調用linux的基本命令的。不過這個類只有在Android的內置ap中才可以使用。單獨寫一個非內置ap的話是無法直接調用android.os.Exec的。間接的方法就是類似上面,用Class.forName("android.os.Exec")來得到這個類,execClass.getMethod("createSubprocess", ... )來得到類里面的方法,這樣就可以使用本來不能用的類了。這就是反射?...
這個方法看起來要麻煩一些,而且比較歪,我覺得還是用java本身提供的東西比較好,畢竟簡單,移植性也好點。
至於自己寫的二進制執行程序如何放到apk里面如何調用,原帖也說的很清楚,不過要提醒一下,assets文件夾對單個文件大小有限制為1MB. 所以如果有資源文件大於1MB我看只好自己先切割一下了,運行的時候再自己拼起來...