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

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?

有帮助吗?

解决方案

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.

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top