【发布时间】:2014-06-29 18:07:13
【问题描述】:
我想执行一些shell commands 并在TextView 中获取输出。该命令可能具有连续输出,例如 ping 或 logcat。此外,TextView 应在实时添加命令输出时自动滚动。
为了做到这一点,我这样做了:
package com.example.rootapp;
import java.io.DataOutputStream;
import java.io.InputStream;
import android.app.Activity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] cmdArray={"logcat -b radio"};
try {
runAsRoot(cmdArray);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void runAsRoot(String[] cmds) throws Exception {
tv=(TextView)findViewById(R.id.cmdOp);
tv.setMovementMethod(new ScrollingMovementMethod());
Process p = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(p.getOutputStream());
InputStream is = p.getInputStream();
for (String tmpCmd : cmds) {
os.writeBytes(tmpCmd+"\n");
int readed = 0;
byte[] buff = new byte[4096];
boolean cmdRequiresAnOutput = true;
if (cmdRequiresAnOutput) {
while( is.available() <= 0) {
try { Thread.sleep(5000); } catch(Exception ex) {}
}
while( is.available() > 0) {
readed = is.read(buff);
if ( readed <= 0 ) break;
String seg = new String(buff,0,readed);
tv.append(seg);
}
}
}
}
}
这工作正常,但它不会持续更新TextView。如您所见,我正在以 root 用户身份执行 radio logcat,输出是连续生成的(已经在终端模拟器和 adb shell 中检查过)。但就我而言,输出不是连续添加的。它在几百行之后停止。
这是我的布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/cmdOp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="bottom"
android:text="@string/hello_world" />
</ScrollView>
</RelativeLayout>
输出应继续滚动 TextView。至少这是我所期望的......请问有什么解决方法吗?
【问题讨论】:
标签: android shell scrollview android-logcat su