在 Android 中調用二進位可執行程式(native executable)

來源:互聯網
上載者:User

前幾天有需要在java代碼中調用二進位程式,就在網上找了些資料,寫點東西記錄下。


Android 也是基於linux
的系統,當然也可以運行二進位的可執行檔。只不過Android
限制了直接的方式只能安裝運行apk檔案。雖然有NDK可以用動態連結程式庫的方式來用C的二進位代碼,但畢竟不方便。至少我們可以調用linux的一些基本
命令,如ls,rm等。

第一種方法:Runtime.exec(String[] args)



這種方法是java語言本身來提供的,在Android裡面也可以使用。args是要執行的參數數組。大概用法如下:


S
tring[] 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 isr
err = new InputStreamReader(stderr);
BufferedReader br
err = new BufferedReader(isr
err);



//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 = br
err.readLine()) != null)
{
result
+= line;
result
+= "/n";

}


i
f( 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")


這個方法是一個老外找到的,原貼在這裡:http://gimite.net/en/index.php?Run%20native%20executable%20in%20Android%20App

代碼大概是這樣:

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我看只好自己先切割一下了,啟動並執行時候再自己拼起來...

    http://blog.csdn.net/liujian885/archive/2009/12/01/4912218.aspx


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.