我想在这个程序中使用线程,因为它在当前状态下使用 UI 线程。当 UI 线程将控制权传递给新创建的线程时,我需要其他进程来使用 UI 线程。
如何在这段代码中使用线程结构?
public class Ping extends Activity implements OnClickListener
{
Button pingButton;
TextView pingText;
EditText pingCommand;
String address;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ping);
pingButton = (Button) findViewById(R.id.bPing);
pingCommand = (EditText) findViewById(R.id.tPingCommand);
pingText = (TextView) findViewById(R.id.tReturnResult);
pingButton.setOnClickListener(this);
}
public void ping()
{
try {
Process process = Runtime.getRuntime().exec("ping -c 8 " + address);
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
int i;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((i = reader.read(buffer)) > 0) {
output.append(buffer, 0, i);
pingText.setText(output);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onClick(View arg0) {
address = pingCommand.getText().toString();
ping();
}
}