简体   繁体   English

如何使用服务或广播接收器的意图?

[英]How to use Intents from a Service or Broadcast Receiver?

I need to be able to handle/catch Intents while my Activity is closed. 我的活动关闭时,我需要能够处理/捕获Intent。 So I am looking at either a Service or a BroadcastReceiver. 所以我正在寻找服务或BroadcastReceiver。

Is it possible to "receive" intents to a service itself? 是否有可能“接收”服务本身的意图? I tried to search, but could not find anything helpful. 我试图搜索,但找不到任何有用的东西。

With a BroadcastReceiver, I am not exactly sure how that works outside of an Activity. 使用BroadcastReceiver,我不确定它是如何在Activity之外工作的。 Does it depend on the Activity being open/running? 它取决于正在打开/运行的活动吗? Can it run by itself? 它可以单独运行吗? Let's say that my Activity is killed by Android(or a task killer app), does the BroadcastReceiver still receive intents and process them? 假设我的Activity被Android(或任务杀手应用程序)杀死,BroadcastReceiver是否仍然接收意图并处理它们?

I have used a BroadcastReceiver as a widget, but I do not want to use a widget this time. 我使用BroadcastReceiver作为小部件,但这次我不想使用小部件。

My goal is to have the user open the Activity to set some options. 我的目标是让用户打开Activity来设置一些选项。 From there, they would be able to close the Activity, but I would still be able to process Intents that were sent out by the system. 从那里,他们将能够关闭活动,但我仍然能够处理由系统发出的Intents。

I am still fairly new to Android development, so I could be so far away from where I need to be. 我仍然是Android开发的新手,所以我可能离我需要的地方太远了。

Am I going about it wrong? 我错了吗?

Broadcast Receivers are application components that can run independent of Activities and Services, so the use-case you describe is definitely supported. 广播接收器是可以独立于活动和服务运行的应用程序组件,因此绝对支持您描述的用例。

If you register an intent-filter tag for the broadcast Intents you want to handle in the receiver manifest node, it will receive all the matching broadcast Intents even if your application process is completely dead (no Activities or Services). 如果为要在receiver清单节点中处理的广播Intents注册intent-filter标记,即使您的应用程序进程完全死亡(没有活动或服务),它也将接收所有匹配的广播Intent。

The following snippet shows how you would add a Broadcast Receiver to your manifest to listen for a broadcast Intent, independent of an Activity or Service running. 以下代码段显示了如何将广播接收器添加到清单以侦听广播的Intent,而不依赖于正在运行的Activity或Service。

<receiver android:name=".MyBroadcastReceiver">
  <intent-filter>
    <action android:name="com.example.project.MY_BROADCAST_ACTION" />
  </intent-filter>
</receiver>

Within your Broadcast Receiver implementation, the onReceive handler will be called when the Intent action for which you specified an intent-filter is broadcast. 在Broadcast Receiver实现中,当您为其指定了intent-filter的Intent操作被广播时,将调用onReceive处理程序。

Note: There are certain system broadcast's that you can't capture this way, but generally speaking this is the approach to take for responding to system events when you have no Activity running. 注意:某些系统广播无法以这种方式捕获,但一般来说,这是在没有Activity运行时响应系统事件的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM