gpt4 book ai didi

Android Dev - 运行 top 命令输出到 TextView

转载 作者:行者123 更新时间:2023-11-30 02:19:25 25 4
gpt4 key购买 nike

我在这个论坛上读了很多书,它对我设置应用程序有很大帮助,但是,我现在还有另一个问题,我想做的是在 TextView 中显示“top”命令输出.所以布局基本上是两个按钮(开始和停止)和一个 TextView ,我在这里读到我必须使用异步任务来运行命令,到目前为止还不错,现在的问题是如何解析输出以便显示正确吗?我想要的结果是一个显示顶级命令结果的小 TextView (与在终端中运行命令的输出相同)

public class Async extends AsyncTask<String, String, Void>
{
private View rootView;
private Activity rootAct;
public Async(View view,Activity act) {
// TODO Auto-generated constructor stub\
View rootView = view;
rootAct = act;
}


@Override
protected void onPreExecute() {
Log.d("PRE-EXECUTE", "OK");
}



@Override
protected void onCancelled() {
Log.d("ON CANCEL", "OK");
}


@Override
protected Void doInBackground(String... params) {
//Execution en BackGround
Log.d("BACKGROUND", "START");
Log.d("BACK PARAM 0", params[0]);
Log.d("BACK PARAM 1", params[1]);

try {
// Executes the command.
Process process = Runtime.getRuntime().exec("top");
// Reads stdout.
// NOTE: You can write to stdin of the command using
// process.getOutputStream().
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
publishProgress(output.toString());


}
reader.close();



return null;

} catch (IOException e) {
throw new RuntimeException(e);
}
}



@Override
protected void onProgressUpdate(String... values) {

Log.d("UPDATE", "START");
Log.d("RESUL", values[0]);

TextView sortie = (TextView) rootAct.findViewById(R.id.txt_output);


sortie.setText(values[0]);




Log.d("UPDATE", "STOP");

}

@Override
protected void onPostExecute(Void result) {
Log.d("POSTEXE", "OK");

}

}

因此,我想要的是我的 textView 显示最上面的命令结果并在每次存在新的“起始”行时更新,但不确定它是否非常清楚,事实上更简单的示例是在您的终端上打开一个终端命令在其中输入 top 电话,我想要完全相同的输出 ...

我希望有人能在那个项目上帮助我! (对不起,我的英语很糟糕,我是法国人 :))

最好的问候,

编辑:事实上,我只需要一种方法来读取缓冲区并将行附加到我的输出,除非连续有 3 个“\n”,这可能吗?

最佳答案

好吧,事实上,下类后我发现的唯一方法是将其解析为“老派”,即使结果并不完美......

while ((line = reader.readLine()) != null) {
if (isCancelled()) {
break;
}
if (line.isEmpty() && i == 2) {
Log.d("BACK", "Retour apres 3 espaces");
publishProgress(output.toString());
output.setLength(0);
i = 0;
} else if (line.isEmpty() && i == 1) {
Log.d("BACK", "2 espaces");
output.append("\n \n");
i = 2;
} else if (line.isEmpty() && i == 0) {
Log.d("BACK", "1 espaces");
output.append("\n \n");
i = 1;
} else {
Log.d("BACK", "LigneTxt");
output.append(line + "\n");
i = 0;
}

这似乎可以完成工作,但数据流并不是真正流畅,因此如果有人有想法,它也不是很完美,我愿意接受任何评论吗?

关于Android Dev - 运行 top 命令输出到 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28813627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com