简体   繁体   English

使用BroadcastReceiver

[英]Working with BroadcastReceiver

I have defined a BroadcastReceiver in my activity in the following way to get results from an IntentService running on another thread: 我已经通过以下方式在我的活动中定义了BroadcastReceiver,以从在另一个线程上运行的IntentService获取结果:

receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            boolean isSyncCompleted = intent.getBooleanExtra("issynccompleted", false);
            if (isSyncCompleted){
                showAlert("Sync completed in service");
            }
            context.unregisterReceiver(receiver);
        }
    };
    //register receiver for service
    registerReceiver(receiver, new IntentFilter(ContentSyncService.SERVICE_INTENT_FILTER));

Note that I am unregistering my receiver in the onReceive code block and not in onPause. 请注意,我正在onReceive代码块中而不是在onPause中注销我的接收器。 That is because I want to have the receiver listening even when the activity has been destroyed. 这是因为即使活动已被破坏,我也希望接收方进行监听。

But I keep getting the error: " Activity ... has leaked IntentReceiver ... that was originally registered here. Are you missing a call to unregisterReceiver()? " 但是我仍然收到错误消息:“ 活动...泄漏了最初在这里注册的IntentReceiver...。您是否缺少对unregisterReceiver()的调用?

This solution works for me, I override the Activity methods, not a BrodcastReceiver: 此解决方案对我有用,我覆盖了Activity方法,而不是BrodcastReceiver:

@Override
protected void onPause() {
    super.onPause();
    // unregister receiver
    LocalBroadcastManager.getInstance(this).unregisterReceiver(
            mMessageReceiver);
}

@Override
protected void onResume() {
    super.onResume();
    // register receiver
    LocalBroadcastManager.getInstance(this).registerReceiver(
            mMessageReceiver, new IntentFilter("your.package.name"));
}

Only will unregister receiver if you receive action at least one time. 如果您至少收到一次操作,只会取消注册接收者。 So you need unregister your receiver in OnPause (and in other place if you need), because there you are safe that always will unregister the receiver. 因此,您需要在OnPause上注销接收器(如果需要,也可以在其他位置注销),因为这样可以确保始终注销接收器。

Intead of use context.unregisterReceiver(receiver) inside your receiver, 接收器内部使用context.unregisterReceiver(receiver)的接口,

Try it: activity.unregisterReceiver(this); 试试看:activity.unregisterReceiver(this);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM