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