gpt4 book ai didi

android - 为什么 LocalBroadcastManager 不能代替 Context.registerReceiver 工作?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:55:30 24 4
gpt4 key购买 nike

我必须为这个应用程序实现一个功能,它由一个 Activity 和一个在后台工作的 Service 组成(它实现了 Service,不是 IntentService)。

看了网上的几个教程,应该可以的,都是用的LocalBroadcastManager,顺便说一下Android推荐的:

If you don't need to send broadcasts across applications, consider using this class with LocalBroadcastManager instead of the more general facilities described below.

我真的浪费了一天的时间来找出为什么它对我不起作用的问题:它只有在我使用 Context.sendBroadcast() 时才有效。和 Context.registerReceiver() 而不是 LocalBroadcastManager 方法。

现在我的应用程序可以正常运行,但我觉得我违背了最佳实践,而且我不知道为什么。知道为什么会发生这种情况吗?

编辑:

在我写完这个问题之后,我进一步研究了这个问题。 LocalBroadcastManager 通过单例工作,我们应该调用 LocalBroadcastManager.getInstance(this).method()。我记录了两个实例(在 ActivityService 中),它们有不同的内存地址。现在我想到了另一个问题,一个 Service 不应该和调用它的 Activity 有相同的 Context 吗?来自 this article服务在主线程上运行,因此我认为 Context 是相同。

有什么想法吗? (很抱歉发了这么长的帖子)

代码示例:

我的服务

public class MyService extends Service {

...

// When an event is triggered, sends a broadcast

Intent myIntent = new Intent(MainActivity.MY_INTENT);
myIntent.putExtra("myMsg","msg");
sendBroadcast(myIntent);

// Previously I was trying:
// LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(myIntent);

}

我的 Activity

public class MainActivity {

...

private BroadcastReceiver messageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("onReceive", "received!");
// TODO something
}
};

@Override
protected void onResume() {
super.onResume();
registerReceiver(messageReceiver, new IntentFilter(MY_INTENT));
// Previously I was trying:
// LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(messageReceiver, new IntentFilter(MY_INTENT));
}
}

最佳答案

我从未使用过 LocalBroadcastManager,但听起来您必须 register your receiver on there (即 lbm.registerReceiver(...),而不是 mycontext.registerReceiver(...))。你在这样做吗?

Now I came to another question, shouldn't a Service have the same Context as the Activity that called it? From this article a Service runs on the Main Thread, hence I'd think the Context would be the same.

Context 类与线程无关。事实上,Service 和 Activity 都是 Context 的(间接)子类——因此它们是它们自己的 Context!
这就是您可以使用“this”作为上下文的原因。

但是无论您将哪个上下文发送到 LocalBroadcastManager.getInstance(),您都应该得到 exact same LBM instance出去。我想不出任何你不这样做的理由——除非你在不同的进程中运行 Activity 和 Service?

关于android - 为什么 LocalBroadcastManager 不能代替 Context.registerReceiver 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29756723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com