Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Android中使用线程_Android_Multithreading - Fatal编程技术网

在Android中使用线程

在Android中使用线程,android,multithreading,Android,Multithreading,我想在这个程序中使用线程,因为它在当前状态下使用UI线程。 当UI线程将控制权传递给新创建的线程时,我需要其他进程来使用UI线程 如何在此代码中使用线程结构 public class Ping extends Activity implements OnClickListener { Button pingButton; TextView pingText; EditText pingCommand; String address; @Override protect

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

试试这个:

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()
试用

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

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