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-23 21:03:33 浏览: 69
这段代码存在一个问题,即网络传输是在主线程中进行的,会导致主线程阻塞,从而影响用户体验。为了避免这个问题,可以将网络传输放到子线程中进行。修改后的代码如下:
```
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();
}
```
这样就可以将网络传输放在子线程中进行,避免阻塞主线程。
阅读全文