What is the right way to register and unregister a listener in order to receive callbacks even when activity is not visible?

StackOverflow https://stackoverflow.com/questions/22662808

Question

I have a service helper singelton, which basically connects an Activity to a Service (sends requests and receives broadcasts and provides a callback interface for the Activity to implement)

The reccomended way is probably to do it onResume() / onPause() like this:

MyActivity extends Activity implements ServiceHelper.Callbacks {

   protected void onResume() {
       super.onResume();
       mServiceHelper.setListener(this);
   }

   protected void onPause() {
       super.onPause();
       // Avoid leaking this Activity
       mServiceHelper.setListener(null);
   }

}

This prevents the leaks, but in thas way the Activity might miss some important callbacks while paused / not visible. Ideally I would do it in onCreate() and onDestroy(), but its stated that the Activity is killable after onPause() so the Activity might get leaked (if I interpret this correctly)

What is the right way to do this?

Était-ce utile?

La solution

onCreate/onDestroy pair is the right one. If the application is getting killed by the system all memory is released so it's not possible to have leaks in that case.

Autres conseils

If you want do some work when your app is active or paused take into account to use a Broadcast Receiver. http://developer.android.com/reference/android/content/BroadcastReceiver.html

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top