Android - 如何接收广播意图ACTION_SCREEN_ON/OFF?
<application>
<receiver android:name=".MyBroadcastReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_SCREEN_ON"></action>
<action android:name="android.intent.action.ACTION_SCREEN_OFF"></action>
</intent-filter>
</receiver>
...
</application>
MyBroadcastReceiver
设置只是为了将 foo 吐到日志中。什么都不做。 请问有什么建议吗?我是否需要分配任何权限来捕获意图?
<application>
<receiver android:name=".MyBroadcastReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_SCREEN_ON"></action>
<action android:name="android.intent.action.ACTION_SCREEN_OFF"></action>
</intent-filter>
</receiver>
...
</application>
MyBroadcastReceiver
is set just to spit foo to the logs. Does nothing.
Any suggestions please? Do I need to assign any permissions to catch the intent?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我相信这些操作只能由在 Java 代码中注册的接收器接收(通过
registerReceiver()
),而不是通过在清单中注册的接收器接收。I believe that those actions can only be received by receivers registered in Java code (via
registerReceiver()
) rather than through receivers registered in the manifest.或者,您可以使用电源管理器来检测屏幕锁定。
Alternatively you can use the power manager to detect screen locking.
上面的三个,他们不能使用Manifest注册。
Android核心向它们添加了“Intent.FLAG_RECEIVER_REGISTERED_ONLY”(也许......我仅在“HEADSET_PLUG”的情况下检查了代码。
所以,我们应该使用“动态寄存器”。
就像下面...
Three of them above, They cannot register using Manifest.
Android core added "Intent.FLAG_RECEIVER_REGISTERED_ONLY" to them (maybe.. I checked codes only in case of "HEADSET_PLUG".
So, We should use "dynamic register".
Like below...
我实现这一点的方法是通过在 onCreate() 中的主要活动中注册接收器,只需预先在某处定义接收器:
然后 onDestroy():
在接收器中,您必须捕获以下情况:
The way I implemented this is by registering the receiver in my main activity in onCreate(), just define the receiver somewhere beforehand:
And then onDestroy():
In receiver you must catch the following cases:
这是 @cmcromance 的 kotlin 版本(感谢您的回答。请不要忘记为原始答案点赞)
Here is the kotlin version of @cmcromance (Thanks for your answer. Please don't forget to upvote the original answer)
新动作键已更新!
New action key updated!