I'm writing an android app using a server. When the user exit the activity (remove it from recent activities) I want to close the connection and do some modifications in the server side before destroying the activity. So I read about the activity life cycle and I found out that I need to write the last call for closing the connections in onDestroy()
. So that what I did:
Main activity:
@Override
public void onDestroy()
{
super.onDestroy();
try {
ConnectionHandler.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Connection Handler:
public static void close() throws IOException {
try {
JSONObject json = new JSONObject();
json.put("client", "close");
mConnectionHandler.new AsyncSendToServer().execute(json.toString());
} catch (JSONException e) {
e.printStackTrace();
}
socket.close();
}
The message transfer is working, but the activity does not execute the ConnectionHandler.close()
method. What should I do to execute this method when the user close the activity?
You have to write the super.onDestroy
after your code. Try:
@Override
public void onDestroy()
{
try {
ConnectionHandler.close();
} catch (IOException e) {
e.printStackTrace();
}
super.onDestroy();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.