在Android中使用线程

时间:2013-02-04 07:39:06

标签: android multithreading

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

3 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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()

答案 2 :(得分:0)

尝试使用runOnUiThread

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

runOnUiThread(new Runnable(){
    @Override
    public void run(){
        // change UI elements here
        //ping()
    }
});