试图让广播接收器没有过滤器

jas*_*ong 4 android broadcastreceiver

IntentFilter intentFilter = new IntentFilter("test");
registerReceiver(mReceiver, intentFilter);
Run Code Online (Sandbox Code Playgroud)

我想没有过滤器,registerReceiver(mReceiver, null)但我的应用程序崩溃了.我可以new IntentFiler()作为空文件管理器吗?

Joh*_*hey 7

因为BroadcastReceiver null在没有匹配的情况下通过来自的标准返回IntentFilter,所以API无法完成您希望完成的任务(我假设正在发送任何和所有广播mReceiver).

你当然可以指定一个空的IntentFilter,但是这将是非常无用的,因为注册接收器不会导致它捕获任何广播(除非它们直接针对接收器,如MisterSquonk在评论中所提到的).否则,您必须确切地知道要使用BroadcastReceiver捕获哪些广播,然后在IntentFilter中指定条件.

  • "...注册接收器不会导致它接收任何广播." - 你确定吗?可以使用清单中的`<receiver>`元素注册一个`BroadcastReceiver`,该元素没有`<intent-filter>`元素.在这种情况下,您通过显式指定其类来向该接收器发送"Intent",就像直接定位"Activity"一样.例如,`Intent i = new Intent(this,MyBroadcastReceiver.class);` (4认同)