@Override public void onClick(View v) { String ip = ipEditText.getText().toString(); int port = Integer.parseInt(portEditText.getText().toString()); new Thread(new Runnable() { @Override public void run() { try { socket = new Socket(ip, port); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); // 获取SeekBar对象 SeekBar progressBar = findViewById(R.id.progressBar); // 添加OnSeekBarChangeListener监听器 progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // 计算百分比对应的数字 int number = progress * 10; out.println(number); } @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) {} }); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }).start();这段代码主线程中设计网络的传输,能帮我移到子线程中吗
时间: 2024-02-10 19:05:44 浏览: 153
是的,这段代码中的网络传输操作是在主线程中进行的,如果需要将其移到子线程中,可以将网络传输操作放在新的线程中执行。可以将上面的代码块修改如下:
```
@Override
public void onClick(View v) {
String ip = ipEditText.getText().toString();
int port = Integer.parseInt(portEditText.getText().toString());
new Thread(new Runnable() {
@Override
public void run() {
try {
socket = new Socket(ip, port);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
// 获取SeekBar对象
SeekBar progressBar = findViewById(R.id.progressBar);
// 添加OnSeekBarChangeListener监听器
progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// 计算百分比对应的数字
int number = progress * 10;
new Thread(new Runnable() {
@Override
public void run() {
out.println(number);
}
}).start();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
}
```
将网络传输操作的代码放在新的线程中执行,SeekBar 的监听器也放在主线程中执行,这样就可以避免在主线程中进行网络传输造成的阻塞问题。
阅读全文