简体   繁体   中英

Runtime.exec() in Android hangs

When I try to exec an external script in this way:

try {
    process = Runtime.getRuntime().exec(
        new String[] { "/system/bin/sh", "./myscript.sh" },
        null,
        "/data/mydir",
    );
} catch (IOException e) {
    Log.e(TAG, e.getMessage(), e);
} catch (SecurityException e) {
    Log.e(TAG, e.getMessage(), e);
}

Sometimes the script gets executed, but most often my app hangs a couple of seconds until Android says my app is unresponsive and it needs to kill it.

My question is, what may be happening. The script is running sometimes, and there is no exception being thrown, it just hangs. I'm at a loss as to what's happening. I'm using Froyo (2.2.1 I think).

Thanks!

According to the documentation you should read the err and out stream of the process.

http://developer.android.com/reference/java/lang/Process.html

I think something like the following will solve your problem.

class Reader extends Thread
{
    InputStream is;

    Reader(InputStream is){
        this.is = is;
    }

    public void run()
    {
        try
        {
            InputStreamReader inStreamReader = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(inStreamReader);
            String line=null;
            while ( (line = br.readLine()) != null){
                // log here   
            }
        } catch (IOException ex){
            ex.printStackTrace();  
        }
    }
}

Use the above class in your code like this

try {
    process = Runtime.getRuntime().exec(
        new String[] { "/system/bin/sh", "./myscript.sh" },
        null,
        "/data/mydir",
    );
    Reader err = new Reader(process.getErrorStream());
    Reader output = new Reader(process.getInputStream());

    err.start();
    outout.start();

} catch (IOException e) {
    Log.e(TAG, e.getMessage(), e);
} catch (SecurityException e) {
    Log.e(TAG, e.getMessage(), e);
} finally {
    process.destroy();
}

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