android 调用 shell命令

调用命令,返回命令输出字符串(执行不了没有权限的命令)

如:run("ls /");

run 实现如下:

 public  synchronized String run(String cmd)        
   throws IOException {  
  StringBuffer result = new StringBuffer();    
  try {       
          
    Runtime runtime = Runtime.getRuntime();      
    Process process = runtime.exec(cmd);         //执行
    InputStream in = process.getInputStream();        
     byte[] re = new byte[1024];            
    while (in.read(re) != -1) {               
     result = result.append(new String(re));             
    }        
   // 关闭输入流       
   if (in != null) {           
    in.close();       
    }    
   }
  catch (Exception ex) {       
   ex.printStackTrace();   
   }    
  return result.toString();
  }

 #####################################33、

本程序能够实现在android中利用system函数执行命令,并将执行结果输出到指定的文件中。 
核心代码: 
hello-jni.c

  1. #include <jni.h>
  2. #include <string.h>
  3. JNIEXPORT jstring Java_com_example_hellojni_HelloJni_system(JNIEnv* env,jobject thiz, jstring str , jstring path)
  4. {
  5. const jbyte* p1 = (*env)->GetStringUTFChars(env , str, NULL);
  6. const jbyte* p2 = (*env)->GetStringUTFChars(env , path, NULL);
  7. char* str2=(char *)p1;
  8. char* path2=(char *)p2;
  9. strcat(str2," > ");
  10. strcat(str2,path2);
  11. system(str2);
  12. return(*env)->NewStringUTF(env,str2);
  13. }
HelloJni.java 
  1. package com.example.hellojni;
  2. import android.app.Activity;
  3. import android.widget.TextView;
  4. import android.os.Bundle;
  5. public class HelloJni extends Activity
  6. {
  7. /** Called when the activity is first created. */
  8. @Override
  9. public void onCreate(Bundle savedInstanceState)
  10. {
  11. super.onCreate(savedInstanceState);
  12. TextView tv = new TextView(this);
  13. tv.setText(system("ls","\"/mnt/sdcard/hello.txt\"") );//这里的第一个参数是要执行的命令,第二个参数是要输出的文件路径
  14. setContentView(tv);
  15. }
  16. public native String system(String str ,String path);
  17. static {
  18. System.loadLibrary("hello-jni");
  19. }
  20. }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值