我在互联网上经历了一些应该工作的教程,他们都使用了LocalBroadcastManager,顺便说一句是Android推荐的:
If you don’t need to send broadcasts across applications,consider
using this class withLocalBroadcastManager
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)); } }
解决方法
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.我想不出你不会有任何理由 – 除非你在不同的流程中运行活动和服务?