简体   繁体   中英

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:

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. 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()? "

This solution works for me, I override the Activity methods, not a 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.

Intead of use context.unregisterReceiver(receiver) inside your receiver,

Try it: activity.unregisterReceiver(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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