我正在尝试制作一个连接到服务器的 Android 应用程序(通过 a Socket
),我相信我需要在不同的线程中完成它。但是,显然,我无法从另一个线程访问或修改 Android UI。我应该怎么办?
package me.nrubin29.quiz.student;
import android.app.Activity;
import android.widget.Toast;
import java.io.EOFException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class Connection {
private Socket socket;
private Thread reader;
private ObjectInputStream inputStream;
private ObjectOutputStream outputStream;
public void initConnection(final Activity activity, final String ip, final String port, final String name) {
new Thread(new Runnable() {
public void run() {
try {
Toast.makeText(activity.getApplicationContext(), "Starting connection to " + ip + ":" + Integer.parseInt(port), Toast.LENGTH_SHORT).show();
socket = new Socket(ip, Integer.parseInt(port));
Toast.makeText(activity.getApplicationContext(), "Connected!", Toast.LENGTH_SHORT).show();
outputStream = new ObjectOutputStream(socket.getOutputStream());
inputStream = new ObjectInputStream(socket.getInputStream());
outputStream.writeObject(name);
reader = new Thread(new Runnable() {
public void run() {
while (true) {
try {
Object in = inputStream.readObject();
System.out.println(in);
}
catch (EOFException e) { Toast.makeText(activity.getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); }
catch (Exception e) { e.printStackTrace(); }
}
}
});
reader.start();
}
catch (Exception e) { e.printStackTrace(); }
}
}).start();
}
}