我想从android应用程序执行shell脚本。我能够通过像ls pwd date等命令:如何在android应用程序中包含shell脚本
process p = Runtime.getRuntime.exec(“command”);
但现在我想执行我的应用程序所需的shell脚本。 shell脚本在linux终端上正常工作。
你能帮助我帮助我在哪里存储shell脚本以及如何从程序调用它?
首先可能吗?
我想从android应用程序执行shell脚本。我能够通过像ls pwd date等命令:如何在android应用程序中包含shell脚本
process p = Runtime.getRuntime.exec(“command”);
但现在我想执行我的应用程序所需的shell脚本。 shell脚本在linux终端上正常工作。
你能帮助我帮助我在哪里存储shell脚本以及如何从程序调用它?
首先可能吗?
从android应用程序执行任意shell脚本听起来像个坏主意 - 但您应该可以将shell脚本放在SD卡上并通过将完整路径传递到SD卡上的文件来执行它。
Environment.getExternalStorageDirectory().getAbsolutePath()
将为您提供SD卡的完整路径。检查以确保它首先安装在:
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
这是一个好主意..我可以想象它的工作.. 但是有没有办法使用sdk,可能包括资产文件夹中的shell脚本或者像添加jar文件等,这使得它方便分发应用程序? – 2012-02-10 06:05:22
你可以做到这一点。您可以像访问其他任何内容一样从您的APK中访问内容。一种方法是将整个shell脚本作为一个字符串加入,并将其从字符串xml中输出。另一种将它作为资源包含并加载的方法。关于SD卡方法的好处是用户可以通过将脚本挂载到他们的计算机上来修改/查看脚本。 – debracey 2012-02-11 21:14:14
非常感谢....现在试试吧...... – 2012-02-14 04:36:06
如果可能,我会强烈建议使用Java和Android SDK来复制脚本的功能。
否则,我认为你需要root,那么你需要做同样的事情到this:
void execCommandLine(String command)
{
Runtime runtime = Runtime.getRuntime();
Process proc = null;
OutputStreamWriter osw = null;
try
{
proc = runtime.exec("su");
osw = new OutputStreamWriter(proc.getOutputStream());
osw.write(command);
osw.flush();
osw.close();
}
catch (IOException ex)
{
Log.e("execCommandLine()", "Command resulted in an IO Exception: " + command);
return;
}
finally
{
if (osw != null)
{
try
{
osw.close();
}
catch (IOException e){}
}
}
try
{
proc.waitFor();
}
catch (InterruptedException e){}
if (proc.exitValue() != 0)
{
Log.e("execCommandLine()", "Command returned error: " + command + "\n Exit code: " + proc.exitValue());
}
}
确实4it支持管道吗?当我尝试runtime.getRuntime.exec(“date | cut -d /”/“-f 1”)它没有工作。 – 2012-02-10 06:27:25
我发现您的权限得到了在shell命令是有限的。你可以在'adb shell'中执行的命令不能在'Runtime.exec'中执行。有人可以解释吗? – 2012-02-10 07:40:32