分析RunTime执行命令以及得到返回值
RunTime执行命令得到返回值
我们有在好好几篇博客里提到过RunTime,比如
而今天同样的,来聊聊RunTime,我们执行这些命令的时候获取到我们的返回值,实际上是比较简单的,但是RunTime的局限性也有点大,很多都没有权限。我们接着看,我现在在终端输入
adb version
看下会输出什么
那我问你,在Android中我们应该怎么去做?我们简单的分析一下,首先,最简单的就是执行语句了
Runtime.getRuntime().exec(cmd);
但是他的工作原理是什么呢?我们都没多大的了解,那我们就去源码里看看
public Process exec(String command) throws IOException {
return exec(command, null, null);
}
他实际上执行的是exec的本类方法,我们继续看:
public Process exec(String command, String[] envp, File dir)
throws IOException {
if (command.length() == 0)
throw new IllegalArgumentException("Empty command");
StringTokenizer st = new StringTokenizer(command);
String[] cmdarray = new String[st.countTokens()];
for (int i = 0; st.hasMoreTokens(); i++)
cmdarray[i] = st.nextToken();
return exec(cmdarray, envp, dir);
}
他这里重载了多个exec,我们继续追踪,但是可以肯定是的是,他的返回时一个Process 对象,好的,继续追我们可以看到
public Process exec(String[] cmdarray, String[] envp, File dir)
throws IOException {
return new ProcessBuilder(cmdarray)
.environment(envp)
.directory(dir)
.start();
}
他最终是new了一个ProcessBuilder去start执行,这里就不往下继续追了,可以看出,他在多个地方有I/O异常,这足以说明了一点,就是他是关于流的操作,那我们肯定是可以我们是能拿到流的,那我们可以直接get了
Process p = Runtime.getRuntime().exec(cmd);
InputStream is = p.getInputStream();
我们看他的源码里知道他的Process 是可以拿到流,那我们尝试一下就能拿到InputStream 先试着去读取一下,那我们的执行代码应该就是这样写:
//执行
private void playRunTime() throws Exception {
String cmd = "adb version";
Process p = Runtime.getRuntime().exec(cmd);
InputStream is = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
tv_result.append(line + "\n");
}
p.waitFor();
is.close();
reader.close();
p.destroy();
}
把这段代码执行下看下是否是能拿到结果:
果不其然,是能拿到的,那样就很好理解RunTime了,一场关于I和O的战斗即将展开,我们看看其他的命令
ls -l
反复的测试了一下,也验证了RunTime了其实局限性还是有的,不过大多数是权限的问题,如果有系统的签名文件的话,那就比较顺利了,不然就只能使用一些简单的命名做做Demo ,而关机,关机什么的,也是需要Root权限的,关于开关机,可以参考我的这篇Blog:
到这里,本片算是OK了,简单的分析了一下过程,Demo就不上传了,直接贴上代码
layout_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="程序启动...."
android:id="@+id/tv_result"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="@color/colorPrimary"
android:textSize="18sp"/>
</ScrollView>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_input_add"/>
</RelativeLayout>
MainActivity
package com.liuguilin.runtimesample;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private TextView tv_result;
private FloatingActionButton fab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
//初始化
private void initView() {
tv_result = (TextView) findViewById(R.id.tv_result);
tv_result.append("\n");
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
playRunTime("ls -l");
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
});
}
//执行
private void playRunTime(String cmd) throws Exception {
Process p = Runtime.getRuntime().exec(cmd);
InputStream is = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
tv_result.append(line + "\n");
}
p.waitFor();
is.close();
reader.close();
p.destroy();
}
}
有兴趣的加群:555974449,我们继续聊聊人生
分析RunTime执行命令以及得到返回值的更多相关文章
- cocos打包出现错误,执行命令出错,返回值:2。 Traceback (most recent call last): File "E:\cocos_workspace\MyGameOne\proj.android\build_native.py", line 43, in <module> build(opts.build_mode) File "E:\cocos_workspace\MyGa
先看看NDK的版本,如果不行,就删除\proj.android\obj\local\armeabi下的文件.
- python 利用python的subprocess模块执行外部命令,获取返回值
有时执行dos命令需要保存返回值 需要导入库subprocess import subprocess p = subprocess.Popen('ping www.baidu.com', shell= ...
- python执行系统命令后获取返回值的几种方式集合
python执行系统命令后获取返回值的几种方式集合 今天小编就为大家分享一篇python执行系统命令后获取返回值的几种方式集合,具有很好的参考价值,希望对大家有所帮助.一起跟随小编过来看看吧 第一种情 ...
- Python中调用Linux命令并获取返回值
方法一.使用os模块的system方法:os.system(cmd),其返回值是shell指令运行后返回的状态码,int类型,0表示shell指令成功执行,256/512表示未找到,该方法适用于she ...
- python执行系统命令后获取返回值
import os, subprocess # os.system('dir') #执行系统命令,没有获取返回值,windows下中文乱码 # result = os.popen('dir') #执行 ...
- C++调用linux命令并获取返回值
qt中封装了相关的方法, 但是因为我的命令中用到了管道命令, 出现了非预期结果, 所有改用了linux系统原生的方法. 下边是一个判断某进程是否存在的例子. 当前存在一个问题,当linux返回多行时, ...
- 【java】并发执行ExecutorService的sumbit返回值的顺序问题
ArrayList<Future> fl = new ArrayList<Future>(); for (int i = 0; i < 10; i++) { Future ...
- sp_executesql得到执行sql语句的返回值
执行 sql语句,得到 变量的值 ' declare @Partition int; ); ); SET @SQLString = N'SELECT @RangeKeyOUT = $PARTITION ...
- ASP.NET 成功执行Update 的 ExecuteNonQuery() 返回值大于0,但是查看数据库却没有改变
//真实姓名保存 $("#TrueNameSaveBtn").click(function () { if ($("#TrueNameSaveText").va ...
随机推荐
- FTP方式发布webservice
以前我发布webservice的步骤是:在 C:\inetpub\wwwroot\路径下发布webservice,然后再在IIS中添加网站并制定路径,这样每次发布了webservice后,需要把发布 ...
- .NET Core Community 首个千星项目诞生:CAP
项目简介 在我们构建 SOA 或者 微服务系统的过程中,我们通常需要使用事件来对各个服务进行集成,在这过程中简单的使用消息队列并不能保证数据的最终一致性, CAP 采用的是和当前数据库集成的本地消息表 ...
- mysql用limit时offset越大时间越长
首先说明一下MySQL的版本:mysql> select version();+-----------+| version() |+-----------+| 5.7.17 |+----- ...
- 运用正则+replace+substring将一段英语的字母大写 angurlar运用自定义指令filter完成首字母大写
复习下js基础并运用正则+replace+substring将一段英语的字母大写 <!DOCTYPE html><html> <head> <meta cha ...
- Spring Boot 之Hello Word
Spring Boot官网:http://projects.spring.io/spring-boot/ 环境准备:maven 3.3.5.jdk8.Idea 1.创建maven项目工程 2.引入st ...
- javaApplication中如何使用log4j
- ●BZOJ 2743 [HEOI2012]采花
题链: http://www.lydsy.com/JudgeOnline/problem.php?id=2743 题解: 树状数组,离线 求区间里面有多少种出现次数大于等于 2 的颜色. 类似某一个题 ...
- 2017ACM/ICPC广西邀请赛-重现赛 1004.Covering
Problem Description Bob's school has a big playground, boys and girls always play games here after s ...
- bzoj2007 NOI2010 网络流转对偶图
2007: [Noi2010]海拔 Time Limit: 20 Sec Memory Limit: 552 MBSubmit: 2775 Solved: 1331[Submit][Status] ...
- python类库numpy中常见函数的用法
1. numpy.reshape 重塑 reshape是一种函数,函数可以重新调整矩阵的行数.列数.维数. B = reshape(A,m,n) 返回一个m*n的矩阵B, B中元素是按列从A中得到的 ...