Alb*_*ore 5 android runtime exec android-2.2-froyo
当我尝试以这种方式执行外部脚本时:
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);
}
Run Code Online (Sandbox Code Playgroud)
有时脚本会被执行,但大多数时候我的应用程序会挂起几秒钟,直到Android说我的应用程序没有响应并且需要将其终止.
我的问题是,可能会发生什么.该脚本是有时运行,有没有被抛出的异常,它只是挂起.我不知道发生了什么.我正在使用Froyo(我认为是2.2.1).
谢谢!
根据文档,您应该阅读该过程的错误和输出流。
http://developer.android.com/reference/java/lang/Process.html
我认为类似下面的内容可以解决您的问题。
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
像这样在代码中使用上面的类
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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3890 次 |
| 最近记录: |