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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top