简体   繁体   中英

how to include a shell script in android app

I wanted to execute shell scripts from an android app. I am able to pass commands like ls pwd date etc by:

process p= Runtime.getRuntime.exec("command");

but now I want to execute a shell script necessary for my app. The shell script works fine on linux terminal.

Can you help me help me where to store the shell script and how to call it from program?

First of all is it possible?

Executing an arbitrary shell script from an android app sounds like a bad idea -- but you should be able to put the shell script on the SD card and execute it by passing the full path to the file on the SD card.

Environment.getExternalStorageDirectory().getAbsolutePath()

will get you the full path to the SD card. Check to make sure it's mounted first with:

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

If possible I would strongly recommend using Java and the Android SDK to replicate your script's functionality.

Otherwise I think you need root, then you need to do something similar to 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());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM