Reputation: 36273
I have an Activity which connects the the server inside onCreate method. Because the connection must stay opened even when I rotate screen I store its reference to the static variable.
Example:
public class Main extends Activity
{
protected static MyConnector connector;
public void onCreate(Bundle savedInstanceState)
{
if (connector == null)
{
connector = new MyConnector();
}
}
}
The connection must stay opened if I open another activity from Main but if I close the Main activity it should be closed.
The problem that I have is I don't know when/how to close the connection. If I close it inside onDestroy it will be destroyed if I rotate screen because the activity is recreated when the orientation changes. If I close it on activity focus it would be closed when I go to the next activity. So... I would like to close it only when I don't need the Main activity and I would like to destroy it for ever.
How would you do that? Thx!
Upvotes: 0
Views: 391
Reputation: 2878
Why not use onConfigChanged() to retain your Activity when Orientation is changed. This way onDestroy() will be called only when the user exits the Activity.
Check Handling the Configuration Change Yourself(at the bottom of the page) to see how to use onConfigChanged().
onConfigChanged
"If your application doesn't need to update resources during a specific configuration change and you have a performance limitation that requires you to avoid the Activity restart, then you can declare that your Activity handles the configuration change itself, which prevents the system from restarting your Activity."
Upvotes: 1