嗨我有一個問題與發送數據到服務器,連接到服務器我使用套接字。要將數據發送到服務器,我使用AsynTask。我有一個問題:Java Android發送數據到服務器應用永遠不會使用onPostExecute()
當應用程序發送數據時,我的應用程序看不到完成此操作,它從不使用onPostExecute()。
這是我的代碼:
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port) {
dstAddress = addr;
dstPort = port;
}
@Override
protected Void doInBackground(Void... arg0) {
// if (pingHost(1000)) {
socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
byte[] theByteArray = message.getBytes();
lengthMessage = (short) theByteArray.length;
outputStream.writeByte((byte) 0xB);
outputStream.writeByte((byte) 0xA);
outputStream.writeByte((byte) 0xA);
outputStream.writeByte((byte) 0xD);
outputStream.writeShort(lengthMessage);
outputStream.write(theByteArray);
outputStream.writeShort(width);
outputStream.writeShort(height);
outputStream.writeInt(lengthbmp);
outputStream.writeInt(lengthResizebmp);
outputStream.writeShort(11);
outputStream.write(imageInByte);
outputStream.write(imageResizeInByte);
outputStream.writeByte((byte) 0xB);
outputStream.writeByte((byte) 0xE);
outputStream.writeByte((byte) 0xE);
outputStream.writeByte((byte) 0xF);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
int bytesRead;
InputStream inputStream = socket.getInputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
outputStream.flush();
outputStream.close();
} catch (UnknownHostException e) {
e.printStackTrace();
isSuccsess = false;
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
e.printStackTrace();
Log.d("la", "nie udało sie");
isSuccsess = false;
response = "IOException: " + e.toString();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (socket != null) {
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(isSuccsess){
Toast.makeText(MainActivity.this, "Zdjęcie zostało wysłane !" , Toast.LENGTH_LONG).show();
bm = null;
clearEt();
ivImage.setImageBitmap(bm);
}
else{
Toast.makeText(MainActivity.this , "Nie udało się wysłać zdjęcia !" , Toast.LENGTH_LONG).show();
}
pbWheel.setVisibility(View.INVISIBLE);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pbWheel.setVisibility(View.VISIBLE);
}
}
請不要再發布您的問題。更好地回答你的第一篇文章的問題http://stackoverflow.com/questions/40679274/java-android-socket-dont-disconnect – greenapps
你檢查了控制檯?我的意思是,有沒有例外? – mallaudin
@mallaudin也沒有例外 –