开发者

How to use Intents from a Service or Broadcast Receiver?

开发者 https://www.devze.com 2022-12-14 06:30 出处:网络
I need to be able to handle/catch Intents while my Activity is closed.So I am looking at either a Service or a BroadcastReceiver.

I need to be able to handle/catch Intents while my Activity is closed. So I am looking at either a Service or a 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. 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?

I have used a BroadcastReceiver as a widget, but I do not want to use a widget this time.

My goal is to have the user open开发者_运维问答 the Activity to set some options. 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.

I am still fairly new to Android development, so I could be so far away from where I need to be.

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).

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.

<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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消