2010-09-24 86 views
0

我試圖使用下面的代碼來運行本機,並且我在類execClass = Class.forName(「android.os.Exec」)中獲取了android.os.exec的classnotfoundexception ..有什麼想法嗎?在Android中運行本機可執行文件錯誤

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 (ClassNotFoundException e) { 
    throw new RuntimeException(e.getMessage()); 
} catch (SecurityException e) { 
    throw new RuntimeException(e.getMessage()); 
} catch (NoSuchMethodException e) { 
    throw new RuntimeException(e.getMessage()); 
} catch (IllegalArgumentException e) { 
    throw new RuntimeException(e.getMessage()); 
} catch (IllegalAccessException e) { 
    throw new RuntimeException(e.getMessage()); 
} catch (InvocationTargetException e) { 
    throw new RuntimeException(e.getMessage()); 
} 

鏈接:http://gimite.net/en/index.php?Run%20native%20executable%20in%20Android%20App

+0

瞭解您使用的Android版本可能會有幫助。 – MatrixFrog 2010-09-24 03:11:47

+0

我正在使用android 2.2 – Jony 2010-09-24 03:22:02

回答

2

android.os.Exec不是公共API的一部分,不應該被使用。自1.6以來它不屬於產品的一部分應該是進一步的激勵。 :-)

您應該使用標準的Java語言工具,例如Runtime.exec()或ProcessBuilder.start()。

相關問題