我有一个Android TCP客户端,它通过Aysnctask与服务器通信,以免冻结UI。我也在测试iBeacons,我正在尝试将iBeacon信息发送到服务器。但是,当我按下连接按钮时,iBeacon范围会冻结,这意味着didRangeBeaconsInRegion(Collection iBeacons,Region region)方法不再有效。如果您发现可能导致此问题的任何内容,请与我们联系。我的asynctask是否意外地影响了用户界面?以下是相关代码:
点击以显示连接按钮:
case R.id.connect:
if(!connect.isChecked()) {
//if(mTcpClient.isConnected) {
mTcpClient.sendMessage("close");
mTcpClient.stopClient();
//}
}
if(connect.isChecked()) {
new ConnectTask().execute("");
sendMsg.setEnabled(true);
msgBox.setEnabled(true);
sendInfo.setEnabled(true);
text.setText("Send a message...");
}
break;
服务器通信的异步任务:
//************************************************************************************
// ASYNCTASK: Creates connection to server
//************************************************************************************
public class ConnectTask extends AsyncTask<String,String,TcpClient> {
@Override
protected TcpClient doInBackground(String... message) {
//we create a TCPClient object
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
@Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
ip = sharedPref.getString("ip_address", "");
port = sharedPref.getString("port", "");
mTcpClient.run(ip, port);
return null;
}
//Provides Progress Updates (when message is received from server)
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
//here we can receive values when called from publishProgress
//this function allows you to update the UI without hanging or any other problems
//when you call your GUI object on it's .notifyDataSetChanged(), it will refresh automatically
text.setText("You got a message!!");
text.setText("Message: ");
toast = Toast.makeText(getBaseContext(), "Received Message: See Message Box", Toast.LENGTH_LONG);
toast.show();
try{ JSONObject jsonReceived = new JSONObject(values[0]);
x = Integer.parseInt(jsonReceived.getString("x"));
y = Integer.parseInt(jsonReceived.getString("y"));
Log.i("TESTING", "x: " + x + "y: " + y);
} catch (Exception je) {}
message.setText(Arrays.toString(values));
plotPoints(x, y);
}
}
所有客户代码:
public class TcpClient {
///SharedPreferences sharedPref; //For Settings to change Ip and Port
public static String SERVER_IP; //your computer IP address
public static int SERVER_PORT;
// message to send to the server
private String mServerMessage;
// sends message received notifications
private OnMessageReceived mMessageListener = null;
// while this is true, the server will continue running
private boolean mRun = false;
// used to send messages
private PrintWriter mBufferOut;
// used to read messages from the server
private BufferedReader mBufferIn;
public static boolean isConnected = false;
JSONObject jsonReceiver;
/**
* Constructor of the class. OnMessagedReceived listens for the messages received from server
*/
public TcpClient(OnMessageReceived listener) {
mMessageListener = listener;
}
/**
* Sends the message entered by client to the server
*
* @param message text entered by client
*/
public void sendMessage(String message) {
if (mBufferOut != null && !mBufferOut.checkError()) {
mBufferOut.println(message);
mBufferOut.flush();
}
}
/**
* Close the connection and release the members
*/
public void stopClient() {
Log.i("Debug", "stopClient");
// send mesage that we are closing the connection
mRun = false;
if (mBufferOut != null) {
mBufferOut.flush();
mBufferOut.close();
}
mMessageListener = null;
mBufferIn = null;
mBufferOut = null;
mServerMessage = null;
isConnected = false;
}
//Run takes two string arguments to specify IP Address and Port number.
public void run(String ipAddr, String port) {
mRun = true;
SERVER_IP = ipAddr;
SERVER_PORT = Integer.parseInt(port);
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVER_PORT);
try {
isConnected = true;
//sends the message to the server
mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//receives the message which the server sends back
mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.i("TCP Client", "Created both Buffers");
//in this while the client listens for the messages sent by the server
while (mRun) {
mServerMessage = mBufferIn.readLine();
if (mServerMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(mServerMessage);
}
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
如果您有任何建议,请与我们联系。谢谢!