我正在尝试编写一种方法,该方法将通过带有基站的 3G 网络向服务器发送消息。IM 尝试多次发送消息,直到我决定停止。但是当我对此进行测试时,它总是在短时间内停止并停止发送消息。有谁知道为什么?
private Runnable commRunnable = new Runnable() {
public void run() {
try {
String message = "Just saying hello!";
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true);
String startReceivingMessage = "Begin sending me data.";
String stopReceivingMessage = "Stop sending me data.";
startSend = false;
stopSend = false;
startReceive = false;
stopReceive = false;
while (!shouldDisconnect) {
if (startSend) {
sendData = true;
startSend = false;
}
if (stopSend) {
sendData = false;
stopSend = false;
}
// Send a message that the server should start transmitting data
// back to us. We only need to transmit this message once.
if (startReceive) {
out.println(startReceivingMessage);
startReceive = false;
receiveData = true;
Thread receiveThread = new Thread(receiveRunnable);
receiveThread.start();
// Tell the server to stop transmitting data.
} else if (stopReceive) {
out.println(stopReceivingMessage);
stopReceive = false;
receiveData = false;
}
if (sendData) {
out.println(message);
}
Thread.sleep(20);
}
} catch (Exception e) {
Log.e("PowerMonitor", e.toString());
} finally {
try {
socket.close();
connected = false;
} catch (Exception e) {
Log.e("PowerMonitor", e.toString());
}
}
}
};
private Runnable receiveRunnable = new Runnable() {
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String reply = "";
Log.d("PowerMonitor", "Starting to receive");
while (receiveData) {
Log.d("PowerMonitor", "Listening...");
reply = in.readLine();
Log.d("PowerMonitor", "Got message: " + reply);
}
} catch (Exception e) {
Log.e("PowerMonitor", e.toString());
}
}
};