Android 从服务接收活动中的数据

Android 从服务接收活动中的数据,android,broadcastreceiver,broadcast,Android,Broadcastreceiver,Broadcast,我已经研究了许多解决其他类似问题的方法,但我不知道我的代码出了什么问题。我知道LocalBroadcast是一种很流行的方法,我花了很多时间尝试实现它。目前,我的清单中没有声明接收者,但据我所知,寄存器行就是用来声明接收者的 在我的活动中: private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, I

我已经研究了许多解决其他类似问题的方法,但我不知道我的代码出了什么问题。我知道LocalBroadcast是一种很流行的方法,我花了很多时间尝试实现它。目前,我的清单中没有声明接收者,但据我所知,
寄存器
行就是用来声明接收者的

在我的活动中:

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("MyActivity", "onReceive");
        String action = intent.getAction();
        int current = intent.getIntExtra("test", 0);
        Toast.makeText(MyActivity.this, current.toString(), Toast.LENGTH_LONG).show();
    }
};

@Override
public void onResume() {
    super.onResume();
    Log.d("MyActivity", "onResume()");
    LocalBroadcastManager.getInstance(MyActivity.this).registerReceiver(
            mMessageReceiver, new IntentFilter("currentUpdate"));
}
@Override
protected void onPause() {
    Log.d("MyActivity", "onPause()");
    LocalBroadcastManager.getInstance(MyActivity.this).unregisterReceiver(mMessageReceiver);
    super.onPause();
}
在服务中,我定义了一个方法:

private void sendNewBroadcast(Intent intent, int current){
    intent.putExtra("test", current);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    Log.d("MyService", "new Broadcast sent from service");
}
我在服务的其他地方也这样使用它:

Intent intent = new Intent("currentUpdate");
sendNewBroadcast(intent, 5);

我已经调试过了,除了“接收”部分外,其他一切都正常工作。我错过什么了吗?服务在不同的活动中启动并正在进行。

首先,广播
Intent
上的操作
字符串
需要与注册接收器的
IntentFilter
上设置的操作相匹配。起初,他们是不同的,但这可能只是一个打字错误


其次,
LocalBroadcastManager
不能跨进程工作。
活动
服务
必须在同一进程中运行,才能使用
LocalBroadcastManager
。如果
服务
需要处于单独的流程中,则必须使用其他机制;e、 例如,
Intent
s,在
Context
上发送和接收的广播,一些支持IPC的事件总线实现,等等

您在
Intent
“test”
“test”中设置的操作与
IntentFilter
“currentUpdate”中的操作不匹配
@MikeM你说得对,我已经更改了,不幸的是没有什么不同。OnReceive仍未触发使用该设置,发送广播时,您的
活动需要在前台运行。是吗?而且,
LocalBroadcastManager
不能跨进程工作。
活动
服务
是否在同一进程中运行?也就是说,是否在清单中的元素上指定了
process
属性?@MikeM,就是这样做的。我没有意识到它们必须在同一个进程中运行,它现在正在工作。如果您添加答案,我们将接受您的答案。谢谢