2014-10-30 127 views
4

在我的应用程序中,我试图执行存在于我的SD卡上的本机代码。如何使用Runtime.getRuntime()。exec(“cmd”)

File sdCard = getExternalFilesDir(null); // directory where native file is placed 
String nativeFile = "nativeFile"; 

String cmd = "shell /system/bin/chmod 0777 " + sdCard.getAbsolutePath() + "/" + nativeFile; 
Process proc = Runtime.getRuntime().exec(cmd); 

但只要Runtime.getRuntime().exec(cmd)被执行时,它抛出错误:

java.io.IOException: Error running exec(). Command: [shell, /system/bin/chmod, 0777, /storage/emulated/0/Android/data/com.example.andridutilproject/files/native] Working Directory: null Environment: null 

任何建议,如何解决这个问题?

+0

没有'shell'可执行文件。你为什么试图运行它? – 2014-10-30 22:22:55

回答

2

首先,您应该将调用exec包装在try-catch-clause中以捕获IOException。

其次,使用exec(java.lang.String[])执行带参数的命令。例如,类似于

Runtime.getRuntime().exec(new String[]{ "shell", "/system/bin/chmod", "0777", sdCard.getAbsolutePath() + "/" + nativeFile }); 
2

Android系统中的sdcard通常被禁止执行。因此,即使正确执行chmod命令,它也会失败。

您可以轻松地测试。通过USB(adb shell)启动shell并执行chmod命令。它会失败并显示错误消息,如“错误模式”。

因此,您必须将文件复制到您有写入权限的其他位置,然后在该副本上设置可执行位。您可以尝试将该文件复制到“/ data/local/tmp /”,但我不确定该路径是否仍然可用。

+2

是否有任何方法可以复制具有现成可执行权限的文件?另外我该如何执行该文件。 – 2014-10-31 05:21:35

+0

通过runtime.exec(..)使用命令“cp”。 – Robert 2014-10-31 09:21:32

相关问题