Android接收器会在应用程序退出时自动取消注册吗?

时间:2010-12-14 07:39:52

标签: android android-activity receiver

当我的Android应用程序需要注册一个接收器时,我一直在Activity.onCreate()注册并在Activity.onDestroy()取消注册(我想我应该使用onPause()和{{ 1}}相反,但这不是重点):

onResume()

取消注册接收器实际上是必要的,还是框架会在我的应用程序退出时处理它?<​​/ p>

2 个答案:

答案 0 :(得分:0)

如果在Activity.onResume()实现中注册接收者,则应在Activity.onPause()中取消注册。 (暂停时不会收到意图,这将减少不必要的系统开销)

答案 1 :(得分:0)

如果使用Android Lifecycle感知组件,则可以在onCreate中处理接收器,并在退出时自动注销接收器

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    handleReceiver(this, new IntentFilter(Intent.ACTION_BATTERY_CHANGED), new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive: intent=" + intent);
        }
    });
}

static <T extends Context & LifecycleOwner> void handleReceiver(T context, IntentFilter intentFilter, BroadcastReceiver receiver) {
    if (context.getLifecycle().getCurrentState() != Lifecycle.State.DESTROYED) {
        context.getLifecycle().addObserver(new LifecycleEventObserver() {
            @Override
            public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
                if (event == Lifecycle.Event.ON_STOP) {
                    context.unregisterReceiver(receiver);
                } else if (event == Lifecycle.Event.ON_START) {
                    context.registerReceiver(receiver, intentFilter);
                } else if (event == Lifecycle.Event.ON_DESTROY) {
                    source.getLifecycle().removeObserver(this);
                }
            }
        });
    }
}