简体   繁体   English

没有调用BroadcastReceiver的onReceive方法

[英]onReceive method of BroadcastReceiver is not getting called

I know there are many SO posts related to this topic but none is working here. 我知道有很多与此主题相关的SO帖子,但没有一个在这里工作。

I am doing sendBroadcast call from the class UserEntry.java: --- 我正在从UserEntry.java类中进行sendBroadcast调用 ---

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 --- 我在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. 因此,用户点击连接按钮, sendBroadcast从类调用UserEntry然后用户切换到类DeviceScanActivityonReceive是永远不会被调用。

You are registering the BroadcastReceiver in DeviceScanActivity.java which means it won't be registered until DeviceScanActivity is active. 您正在DeviceScanActivity.java中注册BroadcastReceiver ,这意味着在DeviceScanActivity处于活动状态之前不会注册它。

In other words the broadcast will simply get lost because there isn't a receiver available to receive the broadcast. 换句话说,广播将简单地丢失,因为没有可用于接收广播的接收器。

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

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