我有一个包含我的服务器的文件,它从客户端应用程序获取内容。如何将服务器收到的内容发送到我的MainActvity? 如果我尝试MainActivity main = new MainActivity();在服务器文件中,应用程序崩溃。
服务器文件。
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
connected_server = true;
} catch (IOException e) {
connected_server = false;
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
@Override
public void run() {
if (msg != null){
//Where I need to send the received content to the main activity
Log.e("INPUT", msg);
}
}
}
Main Activity
public class MainActivity extends Activity {
…
public void message_recieve(String msg){
// do stuff with messages
}
}
答案 0 :(得分:0)
您需要实现回调,以便在服务器请求结束时正确接收结果