为什么Android的LocalBroadcastManager没有运行?

时间:2016-09-20 16:34:31

标签: android localbroadcastmanager

我不知道这段代码有什么问题。

监听器位于活动的onCreate中:

private BroadcastReceiver receiver;
private Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    context = getApplicationContext();

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

            Log.e("MAIN onCreate: ", "It is never shown.");

        }
    };
}

该注册表位于活动的onResumen中:

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(receiver, new IntentFilter("receiveMyService"));
}

发件人在按钮中,我可以看到日志工作正常,但是test的值为false:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        Intent intent = new Intent("receiveMyService");
        Boolean test = LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
        Log.e("Button", "It works but test is always false: " + test);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

为什么BroadcastReceiver的代码 - onReceive永远不会运行?

1 个答案:

答案 0 :(得分:1)

因为您注册了-srcdir而不是BroadcastReceiver
替换这个:

LocalBroadcastReceiver

用这个

registerReceiver(receiver, new IntentFilter("receiveMyService"));