晚上好,所以我正在使用Android Studio开发应用程序,并且想从Raspberry检索终端输出,所以我正在使用JSch进行ssh连接。但是,由于我的树莓派任务是周期性的(以1 Hz的频率),因此我希望在树莓派输出后立即检索终端线。换句话说,我需要在Android函数仍在运行时显示输出以检索以下行。
目前,以下代码仅显示终端输出的第一行,并且出于某种晦涩的原因(对我而言),不显示以下几行! 希望你能帮助我。
以下是我的代码,无法正常运行:
按下发送按钮时,我正在调用“ RetrieveFeedTask”异步任务:
send_button.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
String command = “./SomeProgrammeToExecute”;
String command_type = "send";
new RetrieveFeedTask().execute(command, command_type);
command_edit_text.setText("");
} else if (event.getAction() == MotionEvent.ACTION_UP) {
//Something else
}
return true;
}
});
}
异步任务如下:
class RetrieveFeedTask extends AsyncTask<String, Void, String> {
private Exception exception;
protected String doInBackground(String... params) {
try {
String hostname = "192.168.0.14";
String username = "root";
String password = "pi";
String result = runCommand(hostname, username, password, params[0], params[1]);
return result;
} catch (Exception e) {
this.exception = e;
return e.toString();
}
}
}
并且此类调用一个'runCommand'函数,该函数返回输出String,以及使用输出String设置TextView:
public String runCommand(String hostname, String username, String password, String command, String command_type)
throws JSchException, IOException {
jSch = new JSch();
int port = 22;
session = jSch.getSession(username, hostname, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(30000);
channel = (ChannelExec) session.openChannel("exec");
channel.setPty(true);
channel.setCommand(command);
in = new BufferedReader(new InputStreamReader(channel.getInputStream(), "utf8"));
out = channel.getOutputStream();
channel.connect();
String result_output = "";
if(command_type == "send"){
String line = null;
String current_terminal = "";
while(true) {
line = in.readLine();
if(line != null){
current_terminal = terminal_textView.getText().toString();
result_output = current_terminal + "\n" + result_output + "\n" + line;
terminal_textView.setText(result_output);
}else{
if(channel.isClosed()){
current_terminal = terminal_textView.getText().toString();
result_output = current_terminal + "\n" + result_output + "\n" + channel.getExitStatus();
terminal_textView.setText(result_output);
break;
}else{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
current_terminal = terminal_textView.getText().toString();
result_output = current_terminal + "\n" + result_output + "\n" + e.toString();
terminal_textView.setText(result_output);
}
}
}
}
}
channel.disconnect();
session.disconnect();
return result_output;
}