【问题标题】:how to include a shell script in android app如何在android应用程序中包含一个shell脚本
【发布时间】:2012-02-10 05:45:04
【问题描述】:

我想从一个 android 应用程序执行 shell 脚本。我可以通过以下方式传递 ls pwd date 等命令:

进程 p= Runtime.getRuntime.exec("command");

但现在我想执行我的应用程序所需的 shell 脚本。 shell 脚本在 linux 终端上运行良好。

你能帮我在哪里存储 shell 脚本以及如何从程序中调用它吗?

首先这可能吗?

【问题讨论】:

  • 我发现你在 shell 命令中获得的权限是有限的。很多可以在adb shell 中执行的命令在Runtime.exec 中却无法执行。谁能解释一下?

标签: android shell


【解决方案1】:

从 Android 应用程序执行任意 shell 脚本听起来是个坏主意 - 但您应该能够将 shell 脚本放在 SD 卡上,并通过将完整路径传递到 SD 卡上的文件来执行它。

Environment.getExternalStorageDirectory().getAbsolutePath()

将为您提供 SD 卡的完整路径。检查以确保它首先安装:

Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)

【讨论】:

  • 这是一个好主意..我可以想象它的工作.. 但是 sdk 有没有办法,比如可能在 assets 文件夹中包含 shell 脚本或添加 jar 文件等,以便于分发应用程序?
  • 你可以这样做。您可以像访问其他任何内容一样访问 APK 中的内容。一种方法是将整个 shell 脚本包含为一个字符串,然后将其从字符串 xml 中取出。另一种将其包含为资源然后加载它的方法。 SD卡方法的好处是用户可以通过将脚本安装到他们的计算机来修改/查看脚本。
【解决方案2】:

如果可能的话,我强烈建议使用 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 ") 它没有用。
猜你喜欢
  • 2014-07-21
  • 2018-03-28
  • 2013-03-21
  • 1970-01-01
  • 2019-03-21
  • 1970-01-01
  • 1970-01-01
  • 2012-06-05
  • 2013-07-05
相关资源
最近更新 更多