错误的BroadcastReceiver接收消息

时间:2014-03-14 22:01:35

标签: android

我有2个活动,称它们为A和B.两者都扩展ServiceHelperAbstractActivity,它有一个BroadcastReceiver来接收来自服务的消息。当我启动A时,即使我启动B,一切正常,但如果我尝试从A到B转到A,BroadcastReceiver仍然注册到B.

public ServiceHelperAbstractBase(ServiceHelperListener listener,
        Context context) {

    mListener = listener;
    mContext = context;
}

public BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        String uuidString = intent
                .getStringExtra(ServiceHelper.KEY_INTENT_UUID);

        if (uuidString != null) {
            UUID uuid = UUID.fromString(uuidString);
            processRequestWithUuid(uuid);
        }

        mListener.onRequestDoneProcessing();
    }


};

protected void onPause() {
    ServiceHelper.disconnectReceiver(mContext, mReceiver);
}

protected void onResume() {

    if (this.mRequestDataMap == null) {
        this.mRequestDataMap = new HashMap<UUID, ServiceHelper.RequestData>();
    }

    List<UUID> toCall = new ArrayList<UUID>();

    for (UUID uuid : this.mRequestDataMap.keySet()) {
        toCall.add(uuid);
    }

    for (UUID uuid : toCall) {
        processRequestWithUuid(uuid);
    }

    ServiceHelper.connectReceiver(mContext, mReceiver);
};

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

创建注册广播接收器的功能,并在暂停/恢复方法上取消注册/注册:

//BroadCastReciever variable in base activity or activity
private BroadcastReceiver serviceBroadcastReceiver;         

void registerBroadcastReceiver(){
if (serviceBroadcastReceiver != null)
{

         LocalBroadcastManager.getInstance(this.getActivity()).unregisterReceiver(this.serviceBroadcastReceiver);
            LocalBroadcastManager.getInstance(this.getActivity()).registerReceiver(this.serviceBroadcastReceiver, new IntentFilter("...BROADCAST_STR"));
            return;
        }
        this.serviceBroadcastReceiver = new BroadcastReceiver()
        {
            public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent)
            {
                //Recieve STH
            }
        };
        LocalBroadcastManager.getInstance(this.getActivity()).registerReceiver(this.serviceBroadcastReceiver, new IntentFilter("...BROADCAST_STR"));
    }       //Then onResume & onPause methods in activity   
    @Override
    public void onResume() {
        super.onResume();
        registerBroadcastReceiver();
    }

    @Override
    public void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(this.serviceBroadcastReceiver);
    }