为什么LocalBroadcastManager.getInstance(Context context)需要使用context作为参数? [英] Why does LocalBroadcastManager.getInstance(Context context) require context as a parameter?

查看:80
本文介绍了为什么LocalBroadcastManager.getInstance(Context context)需要使用context作为参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我能够像这样注册接收者:

If I am able to register a receiver like so:

LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("myStringFilter"));

并像这样发送广播:

Intent intent = new Intent("myStringFilter");
LocalBroadcastManager.getInstance(new Activity()).sendBroadcast(intent);

为什么甚至需要Context来获取getInstance?如果我只能说 new Activity()仍然有效,那有什么用呢?

why even require Context for getInstance? If I can just say new Activity() and it still works, what is the point?

推荐答案

现在, LocalBroadcastManager 使用提供的 Context 来调用 getApplicationContext().尽管 new Activity()目前无论您在哪里进行测试都可以使用,但我不会依赖于这种行为必须在所有过去/现在/将来的Android版本上都可以使用.

Right now, LocalBroadcastManager uses the supplied Context for is to call getApplicationContext() on it. While new Activity() may work at present wherever you tested it, I would not rely upon that behavior necessarily working on all past/present/future versions of Android.

LocalBroadcastManager 需要一个 Context ,以便与主应用程序线程的 Handler Looper 一起使用,并且为此使用了 Application (而不是其他一些 Context )来防止内存泄漏.

LocalBroadcastManager needs a Context in order to work with a Handler and Looper for the main application thread, and it uses Application for that (rather than some other Context) to prevent memory leaks.

欢迎您查看

You are welcome to examine the source code to LocalBroadcastManager to learn more about its inner workings.

这篇关于为什么LocalBroadcastManager.getInstance(Context context)需要使用context作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆