微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android – 为什么LocalBroadcastManager不能工作而不是Context.registerReceiver?

我必须为这个应用程序实现一个功能,它包含一个Activity和一个后台工作的服务(它实现了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通过Singleton工作,因为我们应该调用LocalbroadcastManager.getInstance(this).method().我记录了两个实例(在Activity和Service中),它们有不同的内存地址.
现在我来到另一个问题,服务是否应该与调用它的Activity具有相同的Context?从this article开始,服务在主线程上运行,因此我认为Context将是
相同.

有什么想法吗? (对不起,长篇文章)

代码示例:

为MyService

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

}

MyActivity

public class MainActivity {

...

private broadcastReceiver messageReceiver = new broadcastReceiver() {
        @Override
        public void onReceive(Context context,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的(间接)子类 – 所以它们是他们自己的上下文!这就是为什么你可以使用“this”作为上下文.

但无论你发送到LocalbroadcastManager.getInstance()的哪个上下文,你应该得到exact same LBM instance.我想不出你不会有任何理由 – 除非你在不同的流程中运行活动和服务?

原文地址:https://www.jb51.cc/android/316981.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐