没有调用BroadcastReceiver的onReceive方法

时间:2014-05-06 06:26:57

标签: android broadcastreceiver android-broadcast

我知道有很多与此主题相关的SO帖子,但没有一个在这里工作。

我正在从班级 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);

我在班级 DeviceScanActivity.java中定义了我的广播接收器:为---

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);
}

因此,用户点击“连接”按钮,系统sendBroadcast就会调用UserEntry,然后用户切换到课程DeviceScanActivity,永远不会调用onReceive

1 个答案:

答案 0 :(得分:2)

您正在DeviceScanActivity.java中注册BroadcastReceiver,这意味着在DeviceScanActivity处于活动状态之前,它不会被注册。

换句话说,由于没有可用于接收广播的接收器,广播将会丢失。