저는 안드로이드 장치에서 서버로 소켓을 사용하여 데이터를 보내고 역순으로 데이터를 보내고 응용할 것입니다. AsyncTask 클래스를 사용하여 연결을 처리하고 있습니다. 내 문제는 내 주요 활동 클래스의 일부 지점에서 내가 입력 스트림에서 예를 들어 읽을 수있다.AsyncTask, Android를 사용하는 동안 스레드를 동기화 할 때 문제가 발생했습니다.
conhandler = new ConnectionHandler();
conhandler.execute();
Log.i("AppOne", "Reading from stream");
message = conhandler.readFromStream();
는 어떤 일이 내 ConnectionHandler 클래스는 소켓 연결을 설정하기 전에이 코드가 실행된다는 점이다. 이 문제를 해결할 수있는 방법은 무엇입니까? 가 여기 내 ConnectionHandler 클래스에 코드입니다 :
public class ConnectionHandler extends AsyncTask<Void, Void, Void>{
public static String serverip = "192.168.1.100";
public static int serverport = 7777;
Socket s;
public DataInputStream dis = null;
public DataOutputStream dos = null;
public int message;
@Override
protected Void doInBackground(Void... params) {
try {
Log.i("AsyncTank", "doInBackgoung: Creating Socket");
s = new Socket("192.168.1.100", 7777);
} catch (Exception e) {
Log.i("AsyncTank", "doInBackgoung: Cannot create Socket");
}
Log.i("AsyncTank", "doInBackgoung: Socket created");
if (s.isConnected()) {
try {
Log.i("AsyncTank", "doInBackgoung: inside input try");
dis = new DataInputStream(s.getInputStream());
Log.i("AsyncTank", "doInBackgoung: InputStream assigned");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("AsyncTank", "doInBackgoung: Cannot assign Streams, Socket not connected");
e.printStackTrace();
}
try {
Log.i("AsyncTank", "doInBackgoung: inside output try");
dos = new DataOutputStream(s.getOutputStream());
Log.i("AsyncTank", "doInBackgoung: OutputStream assigned");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("AsyncTank", "doInBackgoung: Cannot assign Streams, Socket not connected");
e.printStackTrace();
}
} else {
Log.i("AsyncTank", "doInBackgoung: Cannot assign Streams, Socket is closed");
}
return null;
}
public void writeToStream(double lat, double lon) {
try {
Log.i("AsynkTask", "writeToStream : Writing lat");
dos.writeDouble(lat);
dos.flush();
} catch (Exception e) {
Log.i("AsynkTask", "writeToStream : Writing failed");
}
try {
Log.i("AsynkTask", "writeToStream : Writing lon");
dos.writeDouble(lon);
dos.flush();
} catch (Exception e) {
Log.i("AsynkTask", "writeToStream : Writing failed");
}
}
public int readFromStream() {
try {
if (s.isConnected()) {
Log.i("AsynkTask", "readFromStream : Reading message");
message = dis.readInt();
} else {
Log.i("AsynkTask", "readFromStream : Cannot Read, Socket is closed");
}
} catch (Exception e) {
Log.i("AsynkTask", "readFromStream : Reading failed");
}
return message;
}
}
을 접속의 확립 후에, doInBackground 메소드의 스트림로부터 읽어들입니다. –