1

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.

Jeremy Edwards
  • 14,620
  • 17
  • 74
  • 99

3 Answers3

1

Take a look at Activity.onRetainNonConfigurationInstance() and the associated getLastNonConfigurationInstance() methods - they may be of use.

Squonk
  • 48,735
  • 19
  • 103
  • 135
  • I'm using those but I'm looking for a pattern to help guide me through it. There's a lot of complexity that makes it easy for my app to be hard to maintain because of all these special case considerations. – Jeremy Edwards Dec 06 '10 at 07:10
  • OK but your question is about 'Maintaining a ServiceConnection...through Orientation Changes' but neither the question title or the question itself mentions 'a lot of complexity' nor 'special case considerations'. As you haven't given any examples of how your code works, then it's hard to answer the question. – Squonk Dec 06 '10 at 08:00
1

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.

Romain R.
  • 920
  • 12
  • 21
-2

Use android:configChanges="orientation" in activity property in manifest.

Marek Gocał
  • 555
  • 2
  • 12
  • This approach is not encouraged: http://developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange – ol_v_er Jan 24 '12 at 16:48