1

我想在这个程序中使用线程,因为它在当前状态下使用 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();
  }
}
4

3 回答 3

0

尝试这个:

new Thread(new Runnable(){ public void run(){
   try {
      address = pingCommand.getText().toString();
      int packetNum = packetNumber.getId();
      ping(address,packetNum);
      ping();
      Thread.sleep(5000);
      dialog.dismiss();
   } catch (InterruptedException e) {
      e.printStackTrace();
   }
 }
}).start()
于 2013-02-04T07:54:13.770 回答
0

尝试使用runOnUiThread

在 UI 线程上运行指定的操作。如果当前线程是 UI 线程,则立即执行该操作。如果当前线程不是 UI 线程,则将动作发布到 UI 线程的事件队列中。

runOnUiThread(new Runnable(){
    @Override
    public void run(){
        // change UI elements here
        //ping()
    }
});
于 2013-02-04T07:56:50.100 回答
0

通过使用AsyncTask

public YourTask extends AsyncTask<Object,Object,Object>{ 

    protected void doInBackground(Object o){
        ping();
    }
}

@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub
    address = pingCommand.getText().toString();
    // int packetNum = packetNumber.getId();
    // ping(address,packetNum);
    new YourTask().execute();
}
于 2013-02-04T07:42:23.613 回答