简体   繁体   中英

onReceive method of BroadcastReceiver is not getting called

I know there are many SO posts related to this topic but none is working here.

I am doing sendBroadcast call from the class UserEntry.java: ---

final Intent intent = new Intent(DeviceScanActivity.ACTION_DISCONNECTED);
intent.putExtra(DeviceScanActivity.EXTRAS_DEVICE_NAME, bdDevice.getName());
intent.putExtra(DeviceScanActivity.EXTRAS_DEVICE_ADDRESS,  bdDevice.getAddress());
getActivity().sendBroadcast(intent);

I have defined my broadcast receiver in class DeviceScanActivity.java: as ---

private final BroadcastReceiver mUpdateReceiver = 
new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            device_name = intent.getExtras().getString(DeviceScanActivity.
            EXTRAS_DEVICE_NAME);
            device_address = intent.getExtras().getString(DeviceScanActivity.
            EXTRAS_DEVICE_ADDRESS);
            if (ACTION_CONNECTED.equals(action)) {
                mConnected = "Connected";
                invalidateOptionsMenu();
            } else if (ACTION_DISCONNECTED.equals(action)) {
                mConnected = "Disconnected";
                invalidateOptionsMenu();
            } else if (ACTION_CONNECTING.equals(action)) {
                mConnected = "Connecting";
                invalidateOptionsMenu();
            }
            else
            {
                mConnected = "";
                invalidateOptionsMenu();
            }
        }
    };

@Override
    protected void onResume() {
        super.onResume();

        registerReceiver(mUpdateReceiver, makeUpdateIntentFilter());
}

 @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mUpdateReceiver);
}

So, user clicks connect button and sendBroadcast is called from class UserEntry then user switch to class DeviceScanActivity and still onReceive is never get called.

You are registering the BroadcastReceiver in DeviceScanActivity.java which means it won't be registered until DeviceScanActivity is active.

In other words the broadcast will simply get lost because there isn't a receiver available to receive the broadcast.

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