我試圖製作一個連接到服務器的Android應用程序(通過Socket
),我相信我需要在不同的線程中完成它。但是,顯然,我無法從另一個線程訪問或修改Android UI。我該怎麼辦?Android多線程
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();
}
}
使用'runOnUiThread'這是您的活動類 – Raghunandan
所以每當我想要做的任何事情* * GUI相關的,我應該使用該方法的方法是什麼? – nrubin29
更多信息在這裏; https://developer.android.com/training/multiple-threads/communicate-ui.html – Krylez