Android应用程序如何调用shell脚本(一) |
您所在的位置:网站首页 › Android调用shell命令 › Android应用程序如何调用shell脚本(一) |
package cycle.settings.system;
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader;
import android.util.Log;
public class RuntimeExec { private static final String TAG = "RuntimeExec"; private static final boolean DEBUG = true;//TODO: close this flag
private Process proc; private StreamGobbler outputGobbler = null; private StreamGobbler errorGobbler = null;
static class StreamGobbler extends Thread{ InputStream is; String type; //输出流的类型ERROR或OUTPUT
public StreamGobbler(InputStream is, String type) { // TODO Auto-generated constructor stub this.is = is; this.type = type; }
public void run(){ try { if(DEBUG)Log.d(TAG, "StreamGobbler start"); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; while((line = br.readLine()) != null){ System.out.println(type+">"+line); System.out.flush(); } if(DEBUG)Log.d(TAG, "StreamGobbler end"); } catch (IOException e) { // TODO Auto-generated catch block if(DEBUG)Log.d(TAG, "StreamGobbler exception"); e.printStackTrace(); } } }
/** * * @param cmd : the command * @return success or failure */ public boolean runtimeExec(String cmd){ if(DEBUG)Log.d(TAG, "runtimeExec start");
boolean mboolean = false; try { if(DEBUG)Log.d(TAG, "runtimeExec start1"); Runtime mRuntime = Runtime.getRuntime(); proc = mRuntime.exec(cmd);
//any output message StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(),"OUTPUT"); //any error message StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); //kick them off outputGobbler.start(); //kick them off errorGobbler.start();
int exitVal = proc.waitFor(); if(DEBUG)Log.d(TAG, "process exitValue: "+exitVal);
mboolean = (proc.waitFor()== 0); } catch (Throwable e) { // TODO Auto-generated catch block if(DEBUG)Log.d(TAG, "process exception"); e.printStackTrace(); } return mboolean; }
public void runtimeEND(){ if(DEBUG)Log.d(TAG, "runtimeEND start"); try { if(proc != null){ if(DEBUG)Log.d(TAG, "runtimeEND start1"); proc.getOutputStream().close(); if(DEBUG)Log.d(TAG, "close getOutputStream finish"); proc.getErrorStream().close(); if(DEBUG)Log.d(TAG, "close getErrorStream finish"); proc.destroy(); if(DEBUG)Log.d(TAG, "proc has destory"); } else{ if(DEBUG)Log.e(TAG, "proc is null!!!!!"); } if(DEBUG)Log.e(TAG, "before System.exit(0);"); System.exit(0); if(DEBUG)Log.e(TAG, "after System.exit(0);"); proc = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |