Maintaining a ServiceConnection in Android through Orientation Changes
I have an Activity that holds a ServiceConnection to a Service. When the orientation changes the ServiceConnection appears to get lost and gets re created.
This is not desirable. I'd like to have it such that the ServiceConnection is maintained through the recreation of the Activity. I'm looking for a good开发者_运维百科 pattern that solves this problem.
Take a look at Activity.onRetainNonConfigurationInstance() and the associated getLastNonConfigurationInstance() methods - they may be of use.
Unfortunately, using onRetainNonConfigurationInstance/getLastNonConfigurationInstance can involve leaks. In my case (I use an IntentService to upload a file on a remote server), I was declaring my connection in the considered Activity such as :
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mServiceMessenger = new Messenger(service);
mConnectedToService = true;
}
public void onServiceDisconnected(ComponentName className) {
mConnectedToService = false;
mServiceMessenger = null;
}
};
The mServiceMessenger is an instance of Messenger that allows me to send a cancel order to the upload task.
Nevertheless, when I tested the solution using onRetainNonConfigurationInstance and getLastNonConfigurationInstance, I tracked (thanks to MAT plug-in in Eclipse) that a screen rotation involves a lot of leaks of my Activity context.
To solve this problem (and because my Application complexity allows me to do so), I created a singleton grouping together all the elements I need to handle the connection to my IntentService (and communication with my Activity). So, when rotating the screen, the new Activity created gets back the connection managed by the singleton and can use it without losing information.
Use android:configChanges="orientation" in activity property in manifest.
精彩评论