Chinaunix首页 | 论坛 | 博客
  • 博客访问: 14968
  • 博文数量: 4
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 10
  • 用 户 组: 普通用户
  • 注册时间: 2013-11-16 12:04
文章分类

全部博文(4)

文章存档

2014年(3)

2013年(1)

我的朋友
最近访客

分类: Android平台

2014-01-16 11:33:15

原文地址:Android && 命令行程序 作者:spyhjl

1. 在android 中执行相关Linux 程序 或者 获取相关命令行程序的pid,以下是相关简单的封装:

点击(此处)折叠或打开


  1. import java.io.DataOutputStream;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;

  5. import android.app.Activity;

  6. public class SystemManager extends Activity {

  7.     public static Process RootCommand(String command) {
  8.         Process process = null;
  9.         DataOutputStream os = null;

  10.         try {
  11.             process = Runtime.getRuntime().exec("su");
  12.             os = new DataOutputStream(process.getOutputStream());
  13.             os.writeBytes(command + "\n");
  14.             os.writeBytes("exit\n");
  15.             os.flush();
  16.             process.waitFor();
  17.         } catch (Exception e) {
  18.             DnsServerActivity.displayer("err:" + e.getMessage() + "\r\n");
  19.             return null;
  20.         } finally {
  21.             try {
  22.                 if (os != null) {
  23.                     os.close();
  24.                 }
  25.                  //process.destroy();
  26.             } catch (Exception e) {
  27.                 DnsServerActivity.displayer("err:" + e.getMessage() + "\r\n");
  28.                 return null;
  29.             }
  30.         }
  31.         DnsServerActivity.displayer("Command finished" + "\r\n");

  32.         return process;
  33.     }

  34.     public static String readStreamString(InputStream is) throws IOException {
  35.         StringBuffer localStringBuffer = new StringBuffer();
  36.         InputStreamReader localInputStreamReader = new InputStreamReader(is);
  37.         char[] arrayOfChar = new char[65536];
  38.         int res = 0;
  39.         while (res >= 0) {
  40.             res = localInputStreamReader.read(arrayOfChar);

  41.             if (res >= 0) {
  42.                 localStringBuffer.append(arrayOfChar, 0, res);
  43.             }

  44.         }

  45.         return localStringBuffer.toString();
  46.     }

  47.     public static String execOnce(String cmd) throws IOException {

  48.         java.lang.Process localProcess = Runtime.getRuntime().exec(cmd);

  49.         // String[] args = cmd.split("\\s+");;
  50.         // java.lang.Process localProcess = Runtime.getRuntime().exec(args);

  51.         // java.lang.Process localProcess = Runtime.getRuntime().exec("sh");
  52.         // DataOutputStream os = new
  53.         // DataOutputStream(localProcess.getOutputStream());
  54.         // os.writeBytes(cmd + "\n");
  55.         // os.writeBytes("exit" + "\n");
  56.         // os.flush();

  57.         return readStreamString(localProcess.getInputStream());

  58.     }

  59.     public static int getProcessPid(String processName) {
  60.         try {

  61.             String output = execOnce("ps");
  62.             String[] lines = output.split("\n");

  63.             for (int i = 0; i < lines.length; i++) {
  64.                 // print("line=" + lines[i]);
  65.                 String[] attr = lines[i].split("[\\s]+");

  66.                 // print("attr.length =" + attr.length );
  67.                 if (attr.length != 9)
  68.                     continue;

  69.                 String name = attr[8];
  70.                 int pid = Integer.parseInt(attr[1]);
  71.                 // print("pid=" + pid + ", name=" + name);
  72.                 if (name.equals(processName))
  73.                     return pid;
  74.             }

  75.             return -1;
  76.         } catch (Exception e) {
  77.             e.printStackTrace();
  78.             return -1;
  79.         }
  80.     }

  81. }

 2. 通过简单的页面使用上述的java 类, 实现开控制相关命令行程序的启动,同时打印相关命令行的输出log:

点击(此处)折叠或打开

  1. public class DnsServerActivity extends Activity {
  2.     /** Called when the activity is first created. */

  3.     public static TextView msgEditText;
  4.     public static ScrollView msgScrollView;
  5.     public Process process = null;

  6.     private static final String TAG = "DnsServerActivity";
  7.     public boolean stop_flag = false;
  8.     public static boolean logdisplay = true;

  9.     @Override
  10.     public void onCreate(Bundle savedInstanceState) {
  11.         super.onCreate(savedInstanceState);
  12.         setContentView(R.layout.main);

  13.         msgEditText = (TextView) findViewById(R.id.dns_textview);
  14.         msgScrollView = (ScrollView) findViewById(R.id.dns_msg);

  15.         CheckBox cb = (CheckBox) findViewById(R.id.dns_cb);
  16.         cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

  17.             @Override
  18.             public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
  19.                 if (logdisplay == true) {
  20.                     logdisplay = false;
  21.                 } else {
  22.                     logdisplay = true;
  23.                 }

  24.                 displayer("\r\ndisplay log: " + logdisplay + "\r\n");
  25.             }
  26.         });

  27.         mThread.start();

  28.     }

  29.     public static Handler handler = new Handler();

  30.     public static void displayer(final String content) {
  31.         handler.post(new Runnable() {
  32.             @Override
  33.             public void run() {
  34.                 // msgEditText.append("\r\n");

  35.                 if (logdisplay == false) {
  36.                     return;
  37.                 }

  38.                 msgEditText.append(content);
  39.                 // Toast.makeText(getApplicationContext(), content,
  40.                 // Toast.LENGTH_LONG).show();

  41.                 handler.post(scrollToBottom);
  42.             }
  43.         });
  44.     }

  45.     @Override
  46.     protected void onDestroy() {
  47.         // TODO Auto-generated method stub
  48.         stop_flag = true;

  49.         displayer("dns is onDestroy ... \r\n");
  50.         super.onDestroy();
  51.     }

  52.     public static Runnable scrollToBottom = new Runnable() {
  53.         @Override
  54.         public void run() {
  55.             int off = msgEditText.getMeasuredHeight()
  56.                     - msgScrollView.getHeight();
  57.             if (off > 0) {
  58.                 msgScrollView.scrollTo(0, off);
  59.             }
  60.         }
  61.     };

  62.     private Thread mThread = new Thread() {

  63.         Process process = null;
  64.         int procesId = -1;

  65.         public void run() {
  66.             displayer("\r\nthread is runing in \r\n");

  67.             String dir = getApplicationContext().getFilesDir().getParent();
  68.             String cmd = "." + dir + "/lib/cmdline";
  69.             String pname = "." + dir + "/lib/cmdline";
  70.             

  71.             if ((procesId = SystemManager.getProcessPid(pname)) > 0) {
  72.                 displayer("dns has already run with id --: " + procesId
  73.                         + "\r\n");
  74.                 process = SystemManager.RootCommand("kill " + procesId);
  75.                 process.destroy();
  76.                 process = null;
  77.                 displayer("pthread " + procesId + " has been killed\r\n");
  78.             }

  79.             try {
  80.                 Thread.sleep(5000);
  81.             } catch (InterruptedException e2) {
  82.                 // TODO Auto-generated catch block
  83.                 e2.printStackTrace();
  84.             }

  85.             process = SystemManager.RootCommand(cmd + "&");
  86.             displayer("\r\n\r\nstart cmd: \n" + cmd + "&" + "\r\n\r\n");

  87.             InputStream in = process.getInputStream();
  88.             InputStream errIn = process.getErrorStream();

  89.             LineNumberReader input = new LineNumberReader(
  90.                     new InputStreamReader(in));
  91.             LineNumberReader errorInput = new LineNumberReader(
  92.                     new InputStreamReader(errIn));
  93.             String line = null;

  94.             int errtag = 0;
  95.             int inputag = 0;

  96.             while (!stop_flag) {
  97.                 try {
  98.                     displayer("\r\ndns sever is runnig --- " + "\r\n");

  99.                     if (input.ready() && (line = input.readLine()) != null) {
  100.                         displayer(line);
  101.                         inputag = 1;
  102.                     } else {
  103.                         inputag = 0;
  104.                     }

  105.                     if (errorInput.ready()
  106.                             && (line = errorInput.readLine()) != null) {
  107.                         displayer(line);
  108.                         errtag = 1;
  109.                     } else {
  110.                         errtag = 0;
  111.                     }

  112.                     if (errtag == 0 && inputag == 0) {
  113.                         Thread.sleep(500);
  114.                         displayer("no log in ...\r\n");
  115.                     }

  116.                 } catch (IOException e1) {
  117.                     // TODO Auto-generated catch block
  118.                     e1.printStackTrace();
  119.                     break;
  120.                 } catch (InterruptedException e) {
  121.                     // TODO Auto-generated catch block
  122.                     e.printStackTrace();
  123.                 }

  124.             }

  125.             process.destroy();

  126.             displayer("dns sever is quiting" + "\r\n");

  127.         }
  128.     };
  129. }
 3. android 打包命令行程序可以通过基本的方式,但是还有另外一种方式:例如,如果想打包命令行程序,那么可以将编译生成的命令行程序cmdline 改名为libcmbine.so, 然后将其放入android project 的lib目录下,这样在安装apk后,相应的目录安装目录lib下就可以看到命令行程序libcmbine.so,上述的例子便是基于此完成的。


阅读(1197) | 评论(0) | 转发(0) |
0

上一篇:H.264学习资源

下一篇:没有了

给主人留下些什么吧!~~